Kotlin Array.contentEquals()

Kotlin Array.contentEquals() Tutorial

The Array.contentEquals() function in Kotlin is used to check whether the elements of the calling array are equal to the elements of another specified array. It returns true if the arrays have the same number of same elements in the same order; otherwise, it returns false.

This tutorial will explore the syntax of the contentEquals() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.contentEquals() function is as follows:

fun <T> Array<out T>.contentEquals(
    other: Array<out T>
): Boolean

where

ParameterDescription
otherAnother array.
Parameters of Array.contentEquals()

Examples for Array.contentEquals() function

1. Check if two arrays are equal

In this example, we’ll use the contentEquals() function to compare two arrays: array1 and array2, and check if their contents are equal.

Kotlin Program

fun main() {
    val array1 = arrayOf(1, 2, 3, 4, 5)
    val array2 = arrayOf(1, 2, 3, 4, 5)

    // Printing the given arrays
    println("Array 1:\n${array1.contentToString()}\n")
    println("Array 2:\n${array2.contentToString()}\n")

    // Checking if the two arrays are equal
    if (array1.contentEquals(array2)) {
        println("The two arrays are equal.")
    } else {
        println("The two arrays are not equal.")
    }
}

Output

Array 1:
[1, 2, 3, 4, 5]

Array 2:
[1, 2, 3, 4, 5]

The two arrays are equal.

Now, let us take the elements in arrays such that they are not equal, and rerun the program.

Kotlin Program

fun main() {
    val array1 = arrayOf(1, 2, 3, 4, 5)
    val array2 = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)

    // Printing the given arrays
    println("Array 1:\n${array1.contentToString()}\n")
    println("Array 2:\n${array2.contentToString()}\n")

    // Checking if the two arrays are equal
    if (array1.contentEquals(array2)) {
        println("The two arrays are equal.")
    } else {
        println("The two arrays are not equal.")
    }
}

Output

Array 1:
[1, 2, 3, 4, 5]

Array 2:
[1, 2, 3, 4, 5, 6, 7, 8]

The two arrays are not equal.

Summary

In this tutorial, we’ve covered the Array.contentEquals() function in Kotlin arrays, its syntax, and how to use it to compare the contents of two arrays. This function is handy when you need to verify if the elements of two arrays are identical in order and values.