在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
在Kotlin中没有三元运算符,最封闭的是下面两种情况,
If else作为表达式语句
val a = true if(a) print(" a是真")else print(" a是假")
猫王运营商
如果?:左边的表达式不为空,则猫王操作符 返回它,否则返回右边的表达式。请注意 右边的表达式只在左边的表达式被求值 Side为空。
val name = node.getName() ?: throw IllegalArgumentException("name expected")
参考文档
其他回答
另一个有趣的方法是在以下情况使用:
when(a) {
true -> b
false -> c
}
在一些更复杂的场景中非常方便。老实说,这对我来说比……其他的……
另一种简单的方法
val value : String = "Kotlin"
value ?: ""
这里kotlin本身检查空值,如果它为空,则传递空字符串值。
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
}
您可以在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
}
when替换c类语言的切换操作符。最简单的形式是这样的
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}