saga
saga

Reputation: 2113

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?

Upvotes: 13

Views: 21741

Answers (4)

Venkat Reddy
Venkat Reddy

Reputation: 11

try using listOfNotNull instead of listOf(), it is equivalent to list.filterNotNull()

Upvotes: -1

Edwin Aditya
Edwin Aditya

Reputation: 21

You can't assign a nullable type to a non-nullable type of value. The type-matching maybe works when you assign a value, not after filter operation called.

// the type-matching works before `.filter` is called
val nonNullArr : List<NonNullType> = nullArray//.filter {it != null} 

instead, if you want to do this without an error or without concerning the type. Remove the type from the val, so it goes like this

val nonNullArr = nullArray.filter {it != null} 

Hope it helps

Upvotes: 1

forpas
forpas

Reputation: 164089

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 }

Upvotes: 19

Birju Vachhani
Birju Vachhani

Reputation: 6353

As far as I know, you cannot convert nullable types into nonNull types by just verifying that they are not null. To achieve what you want, you need to manually map nullable values to non-null type by simply creating NonNull type object. For this you can use map extension function.

val nullableArray: Array<String?> = arrayOf("abc", "xyz", null, "efg")

val nonNullList: List<String> = nullableArray.filter { it != null }.map {
    it.toString()
}

Or you can use filterNotNull() method as @forpas suggested in comments

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

Hope it helps you!

Upvotes: 1

Related Questions