解决 Kotlin 类型系统中的 null 安全性限制的惯用方法是什么?
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 }
这个问题只是关于消除空值,也是为了让类型系统认识到空值是通过转换从集合中删除的。
我不想循环,但如果这是最好的方法,我会这样做。
以下编译,但我不确定这是最好的方法:
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)
最佳答案
您可以使用 filterNotNull
这是一个简单的例子:
val a: List<Int?> = listOf(1, 2, 3, null)
val b: List<Int> = a.filterNotNull()
但在底层,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
}
https://stackoverflow.com/questions/38535504/
相关文章:
kotlin - Delegates.notNull 和 lateinit Kotlin 的区别
android - 在 Android Studio 中创建 Kotlin 库
java - 在 Kotlin 中,如何转换 Int?到一个 Int
android - 使用 Kotlin for Android 进行数据绑定(bind)的问题
kotlin - 如何从包类名称字符串中获取 Kotlin KClass?
kotlin - Kotlin 中的普通类和数据类有什么区别?
android - 错误 : supertypes of the following classes