Kotlin:消除List中的空值(或其他功能转换)

问题

在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 }