Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering out non null values from a collection in kotlin

Take a look at this kotlin one liner:

val nonNullArr : List<NonNullType> = nullArray.filter {it != null}

The compiler gives a type error at this line, saying that a list of nullables can't be assigned to a list of non-nulls. But the filter conditional makes sure that the list will only contain non null values. Is there something similar to !! operator that I can use in this situation to make this code compile?

like image 949
saga Avatar asked Feb 15 '19 13:02

saga


People also ask

How do I filter a collection in Kotlin?

To filter collections by negative conditions, use filterNot() . It returns a list of elements for which the predicate yields false . There are also functions that narrow the element type by filtering elements of a given type: filterIsInstance() returns collection elements of a given type.

How do I filter MutableList Kotlin?

The simple approach to filtering a MutableList in-place is to iterate through the list using an iterator and remove the list elements using iterator's remove() function. Please note that ConcurrentModificationException will be thrown if remove() function of MutableList is used instead.

How does Kotlin check not null?

You can use the "?. let" operator in Kotlin to check if the value of a variable is NULL. It can only be used when we are sure that we are refereeing to a non-NULL able value.


1 Answers

It seems logical to assume that the compiler would take into account the predicate

it != null

and infer the type as

List<NonNullType>

but it does not.
There are 2 solutions:

val nonNullList: List<NonNullType>  = nullableArray.filterNotNull()

or

val nonNullList: List<NonNullType>  = nullableArray.mapNotNull { it }
like image 107
forpas Avatar answered Sep 21 '22 16:09

forpas