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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

为什么要用这样的东西:

when(a) {
  true -> b
  false -> b
}

当你实际上可以使用这样的东西(在这种情况下,a是布尔值):

when {
  a -> b
  else -> b
}

其他回答

Kotlin没有三元运算符。你可以使用正则if表达式,如下所示:

If (condition) exp1 else exp2

此外,在Kotlin中if不是语句而是表达式(即它计算为一个值),如果在if分支的主体中有多条语句(或else或else if的主体),块的最后一行就是该分支的值。例如:

if (a>b) {
    println("a is greater than b")
    a // value of this if
} else {
    println("b is greater than a")
    b // value of else
}

when替换c类语言的切换操作符。最简单的形式是这样的

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
        print("x is neither 1 nor 2")
    }
}

您可以定义自己的布尔扩展函数,当布尔值为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 else作为表达式语句

val a = true if(a) print(" a是真")else print(" a是假")

猫王运营商

如果?:左边的表达式不为空,则猫王操作符 返回它,否则返回右边的表达式。请注意 右边的表达式只在左边的表达式被求值 Side为空。

 val name = node.getName() ?: throw IllegalArgumentException("name expected")

参考文档

其他答案中没有提到的一些极端情况。

自从Kotlin 1.1中出现takeIf后,三元运算符a ?B: c也可以这样表示:

b.takeIf { a } ?: c

在c为空的情况下,这将变得更短:

b.takeIf { a }

使b延迟求值的一般解决方法:

true.takeIf { a }?.let { b } ?: c

还要注意,在Java世界中,典型的空检查像value != null ?在Kotlin中转换为value ?: defaultValue。

类似a != null ?B: c可以翻译成a?让{b} ?: c。


看也是布尔?。如果真的建议在KT-6938应该允许简化一个?b: null表达式到a.f iftrue {b}而不提前计算b。