在Kotlin中,与这个表达式等价的是什么?

a ? b : c

这在Kotlin中是无效的代码。


当前回答

你可以这样做:

val ans = (exp1 == exp2) then "yes" ?: "no"

通过使用这个扩展:

infix fun<T> Boolean.then(first: T): T? = if (this) first else null

附注:先不要修改上面的中缀函数接受:T?,表达式就会变得逻辑错误。例:如果你先修改它接受空值:T?,那么val ans = (true == true)那么null ?: "abcd", ans将是"abcd",这将是不正确的。

其他回答

对于我自己,我使用以下扩展函数:

fun T?.or<T>(default: T): T = if (this == null) default else this 
fun T?.or<T>(compute: () -> T): T = if (this == null) compute() else this

第一个函数将在object = null的情况下返回提供的默认值。第二个将在相同情况下计算lambda中提供的表达式。

用法:

1) e?.getMessage().or("unknown")
2) obj?.lastMessage?.timestamp.or { Date() }

就我个人而言,上面的代码比结构内联更具可读性

您可以定义自己的布尔扩展函数,当布尔值为false时返回null,以提供类似于三元运算符的结构:

infix fun <T> Boolean.then(param: T): T? = if (this) param else null

这是a ?B: c表达式翻译成a然后B ?: c,像这样:

println(condition then "yes" ?: "no")

更新: 但是要做一些更类似于java的条件切换,您将需要类似的东西

infix fun <T>布尔值。then(参数:()-> T): T?= if (this) param() else null

Println(条件然后{"yes"} ?: "no") 注意这个。它的内容计算应该推迟,直到我们确定条件为真

这个看起来很笨拙,这就是为什么有很高的要求存在的Java三元运算符移植到Kotlin

您可以在Kotlin中使用if表达式。在Kotlin中if是一个带有结果值的表达式。所以在Kotlin中,我们可以写

fun max(a: Int, b: Int) = if (a > b) a else b

在Java中,我们可以用更大的代码实现同样的效果

int max(int a, int b) {
return a > b ? a : b
}

(x:Int,y:Int):字符串= if (x>y)"max = $x" else "max = $y"

内联funcation

另一种简单的方法

val value : String = "Kotlin"

value ?: ""

这里kotlin本身检查空值,如果它为空,则传递空字符串值。