Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: "if item not in list" proper syntax

Tags:

kotlin

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.

like image 266
Adam Hughes Avatar asked Apr 27 '17 17:04

Adam Hughes


People also ask

How do you check if a string is not in a list Kotlin?

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.

How do I check if an item is in list Kotlin?

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.

What does ?: Mean in Kotlin?

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.


2 Answers

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

like image 186
Yoav Sternberg Avatar answered Sep 22 '22 10:09

Yoav Sternberg


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.

like image 21
zsmb13 Avatar answered Sep 25 '22 10:09

zsmb13