Kotlin - Idiomatic way to check array contains value

jturolla picture jturolla · Feb 14, 2017 · Viewed 98k times · Source

What's an idiomatic way to check if an array of strings contains a value in Kotlin? Just like ruby's #include?.

I thought about:

array.filter { it == "value" }.any()

Is there a better way?

Answer

Geoffrey Marizy picture Geoffrey Marizy · Feb 14, 2017

The equivalent you are looking for is the contains operator.

array.contains("value") 

Kotlin offer an alternative infix notation for this operator:

"value" in array

It's the same function called behind the scene, but since infix notation isn't found in Java we could say that in is the most idiomatic way.