Kotlin – Check if Array Contains Specified Element

To check if an Array contains a specified element in Kotlin language, use Array.contains() method. Call contains() method on this array, and pass the specific search element as argument. contains() returns True if the calling array contains the specified element, or False otherwise.

Syntax

The syntax to call contains() method on Array arr with the search element x passed as argument is

arr.contains(x)

Examples

In the following program, we take an array of strings, and check if this array contains the element "banana" using Array.contains() method.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf("apple", "banana", "cherry")
    val x = "banana"
    if (arr.contains(x)) {
        println("Arrays contains $x.")
    } else {
        println("Array does not contain $x.")
    }
}

Output

Arrays contains banana.

Now, let us take an element in x "kiwi" which is not present in this array, and observe the return value of Array.contains() method.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf("apple", "banana", "cherry")
    val x = "kiwi"
    if (arr.contains(x)) {
        println("Arrays contains $x.")
    } else {
        println("Array does not contain $x.")
    }
}

Output

Array does not contain kiwi.

Conclusion

In this Kotlin Tutorial, we learned how to check if an array contains specified element, using Array.contains() method, in Kotlin programming language with examples.