Problem

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

这个问题不是just个关于消除空值的问题,而是让类型系统认识到通过转换从集合中删除了空值.

我不想循环,但如果这是最好的方式,我会的.

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

下面是一个简单的示例:

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相关问答推荐

如何在Kotlin的嵌套作用域中解析对此的引用

插入/更新/upsert时不发出房间流

为什么Kotlin函数参数名会 destruct 方法调用?

如何使用 Kotlin Maven 更改 Minecraft 插件中的 Shulker GUI 标题

返回 kotlin 中的标签和 lambda 表达式

当 func 重载时,kotlin 如何确定调用哪个 func?

在jetpack compose中将默认方向设置为横向?

如何将 `throw` 放置在辅助函数中但仍然具有空安全性?

使用空键映射获取

我们应该在 Effect 和 Either 之间 Select 哪个作为我们业务服务的返回类型?

如何通过 compose 处理剪切区域?

Kotlin 使用迭代索引过滤 lambda 数组

如何使用 Kotlin KClass 属性 simpleName 生成空值

Android:在 DAO 中使用 Room 数据库和 LiveData 架构

如何使用kotlin中的反射查找包中的所有类

Kotlin中保留的关键字是什么?

如何在Kotlin中使方法param可变?

在 kotlin 中,如何将主构造函数中的属性设置器设为私有?

lateinit 的 isInitialized 属性在伴随对象中不起作用

如何在伴随对象中使用泛型