Kotlin – Check if element is in Array

Check if element is in an Array in Kotlin

To check if specific element is in an Array in Kotlin, you can use in operator.

The syntax of the boolean expression to check if element e is in the Array arr is

e in arr

Examples

Check if “banana” is in the Array

In the following program, we take an Array of strings: fruitNames. We use in operator to check if the element "banana" is in this Array.

Kotlin Program

fun main(args: Array<String>) {
    val fruitNames = arrayOf("apple", "banana", "cherry")
    if ("banana" in fruitNames) {
        println("The element is in array.")
    } else {
        println("The element is not in array.")
    }
}

Output

The element is in array.

Negative Scenario

Let us now take an element that is not in the Array, and programmatically check that.

Kotlin Program

fun main(args: Array<String>) {
    val fruitNames = arrayOf("apple", "banana", "cherry")
    if ("mango" in fruitNames) {
        println("The element is in array.")
    } else {
        println("The element is not in array.")
    }
}

Output

The element is not in array.

We can also store the element in a variable, and form the condition, as shown in the following program.

Kotlin Program

fun main(args: Array<String>) {
    val fruitNames = arrayOf("apple", "banana", "cherry")
    val searchValue = "banana"
    if (searchValue in fruitNames) {
        println("The element is in array.")
    } else {
        println("The element is not in array.")
    }
}

Output

The element is in array.