如果可空类型为空,如何运行代码块?

2024-06-19

在 Kotlin 中,如果对象不为 null,我可以运行代码,如下所示:

data?.let {
    // execute this block if not null
}

但是如果对象为空,我该如何执行代码块呢?


您可以使用elvis操作员 https://kotlinlang.org/docs/reference/null-safety.html#elvis-operator并评估另一个代码块run { ... }:

data?.let {
    // execute this block if not null
} ?: run {
    // execute this block if null
}

但这似乎不像简单的那样具有可读性if-else陈述。

此外,您可能会发现此问答很有用:

  • 在 Kotlin 中,处理可为空值、引用或转换它们的惯用方法是什么 https://stackoverflow.com/questions/34498562/in-kotlin-what-is-the-idiomatic-way-to-deal-with-nullable-values-referencing-o
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果可空类型为空,如何运行代码块? 的相关文章

随机推荐