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.
Method 2: Using find or first: find can be used to find a specific element in a list using a predicate. Using the predicate, we can check if any element is equal to a string. It returns the first element that matches the given predicate. It returns null if the element is not found in the list.
To check if a specific element is present in this List, call contains() function on this List object and pass given element as argument to this function. The Kotlin List. contains() function checks if the list contains specified element and returns a boolean value.
In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.
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
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.
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