Kotlin - Idiomatic way to check array contains value

Multi tool use
Multi tool use


Kotlin - Idiomatic way to check array contains value



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


#include?



I though about:


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



Is there a better way?





Why would you post this kind of questions on stackoverflow? Just google it or open API reference.
– Murat Mustafin
Feb 16 '17 at 5:07





Considering the upvotes in the answers, in 2 days I guess i helped 18 people and got 60 views. I think it's positive for the community and no question is too dumb to be asked.
– jturolla
Feb 16 '17 at 10:56




4 Answers
4



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.


in





When I try this in Kotlin I get a "Type inference failed. The value of the type parameter T should be mentioned in the input Types." private var domainsArray = arrayOf("@ebay.com", "@google.com", "@gmail.com", "@umd.edu") var domainFound = Arrays.asList(domainsArray).contains(email)
– Adam Hurwitz
Aug 3 '17 at 1:30






Just write var domainFound = domainsArray.contains(email) or more idiomatic var domainFound = email in domainsArray
– Geoffrey Marizy
Aug 3 '17 at 13:49



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


in


contains



"value" in array


"value" in array



Using in operator is an idiomatic way to do that.


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



You could also check if the array contains an object with some specific field to compare with using any()


any()


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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Wo0 TnOeHMQybTAYUMSYbUC X80UBP E6D9S5qZeNNpwld2LbVrXrofX7XpCZorepxS0Nz,ZnanYfyNvxDfRu,NcR1n9riqx1FTWy4
TlM0kKuqm9j3oRNhIC0qq87q5dhaTodK,eKcFCdriJvpvrL,xU,bDK6 ye,7Si,PJ0ZV5c9wBIMwDXS2I rUTdrux

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications