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

在 Kotlin 中,如果对象不为 null,我可以像这样运行代码:

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

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

最佳答案

您可以使用 elvis operator并使用 run { ... } 评估另一段代码:

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

但这似乎不像简单的 if-else 语句那样可读。

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

  • In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them

https://stackoverflow.com/questions/45800036/

相关文章:

java - Kotlin 中字段的 `open` 关键字是什么?

kotlin - Kotlin 中的 'open' 和 'public' 有什么区别?

android - 无法设置约束组的可见性

kotlin - 在 Kotlin 中使用接口(interface)的默认函数实现

java - 在使用 Kotlin 的方法中抛出异常

android - android 上的 Kotlin : Cannot find main mer

function - Kotlin:你可以为可变参数使用命名参数吗?

android - IllegalArgumentException : savedInstance

class - 我无法从 Kotlin 的嵌套类中联系到任何类成员

java - Kotlin 中的 Lambda 表达式