Filtering out non null values from a collection in kotlin
Asked Answered
M

4

12

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?

Morganica answered 15/2, 2019 at 13:20 Comment(1)
Use nullArray.filterNotNull() instead.Mosque
M
17

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 }
Mosque answered 15/2, 2019 at 13:36 Comment(2)
what if List has no-null objects but i want to filter based on some key of that object whose value is null. How about doing that ?Marchetti
@Marchetti first map the list to the key, then filter not null and filter original list according to result equality.Huggins
H
1

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!

Hairsplitter answered 15/2, 2019 at 13:35 Comment(0)
H
1

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

Habergeon answered 16/2, 2019 at 15:11 Comment(0)
T
-1

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

Thrower answered 24/12, 2020 at 8:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.