Kotlin: eliminate nulls from a List (or other functional transformation)

假如想象 提交于 2019-12-30 16:18:33

问题


Problem

What is the idiomatic way of working around this limitation of the null-safety in the Kotlin type system?

val strs1:List<String?> = listOf("hello", null, "world")

// ERROR: Type Inference Failed: Expected Type Mismatch:
// required: List<String>
// round:    List<String?>
val strs2:List<String> = strs1.filter { it != null }

This question is not just about eliminating nulls, but also to make the type system recognize that the nulls are removed from the collection by the transformation.

I'd prefer not to loop, but I will if that's the best way to do it.

Work-Around

The following compiles, but I'm not sure it's the best way to do it:

fun <T> notNullList(list: List<T?>):List<T> {
    val accumulator:MutableList<T> = mutableListOf()
    for (element in list) {
        if (element != null) {
            accumulator.add(element)
        }
    }
    return accumulator
}
val strs2:List<String> = notNullList(strs1)

回答1:


You can use filterNotNull

Here is a simple example:

val a: List<Int?> = listOf(1, 2, 3, null)
val b: List<Int> = a.filterNotNull()

But under the hood, stdlib does the same as you wrote

/**
 * Appends all elements that are not `null` to the given [destination].
 */
public fun <C : MutableCollection<in T>, T : Any> Iterable<T?>.filterNotNullTo(destination: C): C {
    for (element in this) if (element != null) destination.add(element)
    return destination
}



回答2:


you can also use

mightContainsNullElementList.removeIf { it == null }


来源:https://stackoverflow.com/questions/38535504/kotlin-eliminate-nulls-from-a-list-or-other-functional-transformation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!