65

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.

4 Answers 4

128

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

2
  • Thank you for this Apr 27, 2017 at 17:29
  • 3
    @AdamHughes Also, it is the same for is-check: its negation is !is.
    – hotkey
    Apr 27, 2017 at 17:46
28

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.

1
  • Ah, I never saw this operator overloading doc, thank you. Apr 27, 2017 at 17:29
0

!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 }
-4
if (myList!!.contains(x)){

    }

if (!myList!!.contains(x)){

    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.