问题描述
问题
在Kotlin类型系统中,解决这种零安全限制的习惯方法是什么?
val strs1:List< String?> = listOf(hello,null,world)
//错误:类型推断失败:期望类型不匹配:
//所需:列表< String>
// round:List< String?>
val strs2:List< String> = strs1.filter {it!= null}
这个问题不是 关于消除空值,但也使类型系统认识到,通过转换从集合中删除空值。
我不想循环,但我如果这是最好的办法。
解决方法
以下编译,但我'我不确定这是做到这一点的最佳方式:
fun< T> notNullList(list:List< T>):List< T> {
val accumulator:MutableList< T> (元素在列表中){
if(element!= null){
accumulator.add(element)
}
} $ b $ = $ mutableListOf b返回累加器
}
val strs2:List< String> = notNullList(strs1)
=https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter-not-null.html =nofollow noreferrer> filterNotNull
下面是一个简单的例子:
val a:List< Int?> = listOf(1,2,3,null)
val b:List< Int> = a.filterNotNull()
但是,stdlib和你写的一样
/ **
*将所有不为null的元素追加到给定的[destination]。
* /
public fun< C:MutableCollection< in T>,T:Any>如果(元素!= null)destination.add(元素)
返回目的地
}(可选的)< T→> .filterNotNullTo(destination:C):C {
Problem
What is the idiomatic way of working around this limitation of the null-safety in the Kotlin type system?
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 }
This question is not just about eliminating nulls, but also to make the type system recognize that the nulls are removed from the collection by the transformation.
I'd prefer not to loop, but I will if that's the best way to do it.
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)
You can use filterNotNull
Here is a simple example:
val a: List<Int?> = listOf(1, 2, 3, null)
val b: List<Int> = a.filterNotNull()
But under the hood, stdlib does the same as you wrote
/**
* 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
}
这篇关于Kotlin:消除List中的空值(或其他功能转换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!