在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)