Kotlin - The idiomatic way to validate an array contains a value

What an idiomatic way to check if a string array contains a value in kotlin? As well as ruby #include?.

At least about:

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

Is there a better way?

+26
source share
5 answers

The equivalent you are looking for is the operator contains .

array.contains("value") 

Kotlin offers an alternative infix notation for this statement:

"value" in array

This is the same function that is called backstage, but since infix notation is not found in Java, we can say that this inis the most idiomatic way.

+30
source

, any()

listOfObjects.any{ object -> object.fieldxyz == value_to_compare_here }
+43

You can use the operator in, which in this case calls contains:

"value" in array

+18
source

Using an operator in is an idiomatic way to do this.

val contains = "a" in arrayOf("a", "b", "c")
+13
source

Here is the code where you can find a specific field in an ArrayList with objects. Amar Jain's answer helped me:

listOfObjects.any{ it.field == "value"}
0
source

Source: https://habr.com/ru/post/1669738/


All Articles