Filter non null elements


#1

Lets say I have a list of Int and null values, so that the type of the list is List<Int?>. Now I want to filter all elements being not null. Or, expressed in Scala, I want something like this:

scala> List(Some(1), Some(2), None, Some(4)).flatten
res0: List[Int] = List(1, 2, 4)

My attempt with Kotlin was this:

val nullableList = listOf(1, 2, null, 4)
val intList: List<Int> = nullableList.filter { it != null }

But then I get “Type inference failed. Expected type mismatch: inferred type is
kotlin.collections.List<kotlin.Int?> but kotlin.collections.List<kotlin.Int> was expected”.

Is there a convenient way to filter non-null elements and get a list of that type?


#2

I’ve just found it:

val intList: List<Int> = nullableList.filterNotNull()

#3

You were getting error because listOf(1, 2, null, 4) creates List<Int?>, and in your second line, the returning collection from .filter{ it != null} will also be typeof List<Int?>. Answered for somebody else in future :smile: