Problem
在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 }
这个问题不是just个关于消除空值的问题,而是让类型系统认识到通过转换从集合中删除了空值.
我不想循环,但如果这是最好的方式,我会的.
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)