相关疑难解决方法(0)

Kotlin:消除列表中的空值(或其他功能转换)

问题

在Kotlin类型系统中解决零安全限制的惯用方法是什么?

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 }
Run Code Online (Sandbox Code Playgroud)

这个问题不仅仅是关于消除空值,还要使类型系统认识到转换中从集合中删除了空值.

我宁愿不循环,但如果这是最好的方法,我会这样做.

变通

以下编译,但我不确定这是最好的方法:

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)
Run Code Online (Sandbox Code Playgroud)

types nullable filter kotlin

23
推荐指数
1
解决办法
5800
查看次数

标签 统计

filter ×1

kotlin ×1

nullable ×1

types ×1