In Kotlin, how to check contains one or another value?

This is the shortest and most idiomatic way I can think of using any and in:

val values = setOf(2, 3)
val array = intArrayOf(1, 2, 3)

array.any { it in values }

Of course you can use a functional reference for the in operator as well:

array.any(values::contains)

I use setOf for the first collection because order does not matter.

Edit: I switched values and array, because of alex.dorokhow's answer. The order doesn't matter for the check to work but for performance.


The OP wanted the most idiomatic way of solving this. If you are after a more efficient way, go for aga's answer.


I'd use any() extension method:

arrayOf(1, 2, 3).any { it == 2 || it == 3 }

This way, you traverse the array only once and you don't create a set instance just to check whether it's empty or not (like in one of other answers to this question).


You can use intersect method, it takes iterable as paramter and returns set containing only items that are both in your collection and in iterable you provided. Then on that set you just need to do size check.

Here is sample:

val array1 = arrayOf(1, 2, 3, 4, 5, 6)
val array2 = arrayOf(2, 5)

// true if array1 contains any of the items from array2
if(array1.intersect(array2.asIterable()).isNotEmpty()) {
    println("in list")
}

Tags:

Arrays

Kotlin