In Kotlin we can do:
val arr = intArrayOf(1,2,3) if (2 in arr) println("in list")
But if I want to check if 2 or 3 are in arr
, what is the most idiomatic way to do it other than:
if (2 in arr || 3 in arr) println("in list")
To check if a string contains specified string in Kotlin, use String. contains() method.
contains() Function. The Kotlin List. contains() function returns true if element is found in the list, else false.
Kotlin has two types of lists, immutable lists (cannot be modified) and mutable lists (can be modified). Read-only lists are created with listOf() whose elements can not be modified and mutable lists created with mutableListOf() method where we alter or modify the elements of the list.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With