Gle*_*son 23 types nullable filter 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)
Ser*_*rCe 48
您可以使用 filterNotNull
这是一个简单的例子:
val a: List<Int?> = listOf(1, 2, 3, null)
val b: List<Int> = a.filterNotNull()
Run Code Online (Sandbox Code Playgroud)
但在引擎盖下,stdlib和你写的一样
/**
* 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
}
Run Code Online (Sandbox Code Playgroud)