Kotlin:从列表(或其他功能转换)中消除空值 [英] Kotlin: eliminate nulls from a List (or other functional transformation)

查看:42
本文介绍了Kotlin:从列表(或其他功能转换)中消除空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决 Kotlin 类型系统中 null-safety 的这种限制的惯用方法是什么?

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.

以下编译,但我不确定这是最好的方法:

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)

推荐答案

您可以使用 filterNotNull

这是一个简单的例子:

val a: List<Int?> = listOf(1, 2, 3, null)
val b: List<Int> = a.filterNotNull()

但在幕后,stdlib 和你写的一样

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:从列表(或其他功能转换)中消除空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆