Search code examples
kotlinnullnullablekotlin-null-safety

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?


Solution

  • 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 }