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?