Kotlin: "if item not in list" proper syntax

Kotlin

Kotlin 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)){
        
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam HughesView Question on Stackoverflow
Solution 1 - KotlinYoav SternbergView Answer on Stackoverflow
Solution 2 - Kotlinzsmb13View Answer on Stackoverflow
Solution 3 - KotlinGiboltView Answer on Stackoverflow
Solution 4 - KotlinInfoBook TechnologiesView Answer on Stackoverflow