用于计算值的 Elvis 运算符

Pag*_*und 2 kotlin

在 Kotlin 中,我们可以像这样使用 Elvis 运算?:符:

val string: String = null ?: "something else"
Run Code Online (Sandbox Code Playgroud)

但是如果“其他东西”是计算的结果呢,比如

val string: String = null ?: {
    // do some comutations here
    "something else"
}
Run Code Online (Sandbox Code Playgroud)

这不会编译,因为 is 的右侧?:是一个函数() => String而不是String

我有一种感觉,我需要使用其中一个函数等takeIftakeUnless但我不明白。

谢谢

mar*_*ran 7

使用run- 函数。它执行计算并返回结果。

val string: String = null ?: run {
    // do some computations here
    "something else"
}
Run Code Online (Sandbox Code Playgroud)