This article explores different ways to check if an array contains an element in Kotlin.

1. Using In operator

The recommended way to check if an array contains an element is using the in operator, which provides concise and readable syntax.

Download Code

 
The in operator is equivalent to calling the contains() function, since the expression x in y is translated to y.contains(x). The contains() function returns true if the element is found in the array.

Download Code

2. Using any() function

We can check if any element of the array matches the given value using the any() function. Its usage is demonstrated below:

Download Code

 
We can also compare the array against multiple objects using the any() function, as follows:

Download Code

3. Using filter() function

Another approach is to retain all occurrences of the specified element in the array using the filter() function. Then, we can call the isNotEmpty() function to determine if that element is found or not.

Download Code

 
Alternately, we can use the count() function to get the count of the specified element in the array:

Download Code

4. Using find() function

The find() function returns the first element matching the given predicate, or null if no such element was found. We can use it as follows to determine if a value is present in the array.

Download Code

That’s all about checking if an array contains an element in Kotlin.