Kotlin:从列表中消除空值(或其他功能转换)
Kotlin: eliminate nulls from a List (or other functional transformation)
问题
解决 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 }
这个问题不仅仅是关于消除空值的问题,也是为了让类型系统认识到空值是通过转换从集合中删除的。
我不想循环,但如果这是最好的方式,我会的。
解决方法
以下编译,但我不确定这是最好的方法:
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
}
你也可以使用
mightContainsNullElementList.removeIf { it == null }
val strs1 = listOf("hello", null, "world") // [hello, null, world]
val strs2 = strs1.filter { !it.isNullOrBlank() } // [hello, world]
问题
解决 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 }
这个问题不仅仅是关于消除空值的问题,也是为了让类型系统认识到空值是通过转换从集合中删除的。
我不想循环,但如果这是最好的方式,我会的。
解决方法
以下编译,但我不确定这是最好的方法:
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
}
你也可以使用
mightContainsNullElementList.removeIf { it == null }
val strs1 = listOf("hello", null, "world") // [hello, null, world]
val strs2 = strs1.filter { !it.isNullOrBlank() } // [hello, world]