Kotlin: "if item not in list" proper syntax
KotlinKotlin Problem Overview
Given Kotlin's list lookup syntax,
if (x in myList)
as opposed to idiomatic Java,
if (myList.contains(x))
how can one express negation? The compiler doesn't like either of these:
if (x not in mylist)
if !(x in mylist)
Is there an idiomatic way to express this other than if !(mylist.contains(x)))
? I didn't see it mentioned in the Kotlin Control Flow docs.
Kotlin Solutions
Solution 1 - Kotlin
Use x !in list
syntax.
The following code:
val arr = intArrayOf(1,2,3)
if (2 !in arr)
println("in list")
is compiled down to the equivalent of:
int[] arr = new int[]{1, 2, 3};
// uses xor since JVM treats booleans as int
if(ArraysKt.contains(arr, 2) ^ true) {
System.out.println("in list");
}
The in
and !in
operators use any accessible method or extension method that is named contains
and returns Boolean
. For a collection (list, set...) , it uses collection.contains
method. For arrays (including primitive arrays) it uses the extension method Array.contains
which is implemented as indexOf(element) >= 0
Solution 2 - Kotlin
The operator for this in Kotlin is !in
. So you can do
if (x !in myList) { ... }
You can find this in the official docs about operator overloading.
Solution 3 - Kotlin
!in with matching data classes
Although ==
will compare duplicated data classes as equal, !in
doesn't consider duplicate copies to be the same.
Here is my solution:
// Create a set of hashcodes
val itemHashes = myCollection.map { it.hashCode() }.toSet()
// Use !in with the set
item.hashCode() !in itemHashes
// For comparing a whole collection
myCollection.filter { it.hashCode() !in itemHashes }
Solution 4 - Kotlin
if (myList!!.contains(x)){
}
if (!myList!!.contains(x)){
}