Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

kotlin

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") 
like image 896
ADev Avatar asked Jan 04 '18 13:01

ADev


People also ask

How do I check if a string contains in Kotlin?

To check if a string contains specified string in Kotlin, use String. contains() method.

How does Kotlin's contain work?

contains() Function. The Kotlin List. contains() function returns true if element is found in the list, else false.

What is listOf in Kotlin?

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.


2 Answers

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).

like image 71
aga Avatar answered Sep 29 '22 08:09

aga


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.

like image 33
Willi Mentzel Avatar answered Sep 29 '22 07:09

Willi Mentzel