在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
在Kotlin中,if是一个表达式,即它返回一个值。因此 没有三元操作符(条件?然后:else),因为 普通的如果在这个角色中表现得很好。这里的手动源代码
// Traditional usage
var max = a
if (a < b) max = b
// With else
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// As expression
val max = if (a > b) a 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
}
博士TL;
if (a) b else c
^是你可以用来代替三元运算符表达式a ?b: c,这是Kotlin语法不允许的。
在Kotlin中,许多控制语句,例如if、when,甚至try,都可以用作表达式。因此,这些语句的结果可以赋值给变量,也可以从函数返回,等等。
从语法上讲,不需要三元运算符
由于使用了Kotlin的表达式,该语言实际上并不需要三元运算符。
if (a) b else c
你可以用什么来代替三元运算符表达式a ?B: c。
我认为前一种表达更有可读性,因为每个人都知道如果其他人做了什么,然而?:如果您不熟悉语法,则不太清楚。
然而,我不得不承认,我经常错过更方便的三元运算符。
其他备选方案
when
您还可以看到在检查条件时Kotlin中使用的构造。这也是一种以另一种方式表达if-else级联的方法。下面以OTs为例。
when(a) {
true -> b
false -> c
}
扩展
正如其他答案中的许多好例子(Kotlin三元条件运算符)所示,扩展还可以帮助解决您的用例。
使用以下中缀函数,我可以覆盖许多常见的用例,几乎与在Python中实现的方式相同:
class TestKotlinTernaryConditionalOperator {
@Test
fun testAndOrInfixFunctions() {
Assertions.assertThat(true and "yes" or "no").isEqualTo("yes")
Assertions.assertThat(false and "yes" or "no").isEqualTo("no")
Assertions.assertThat("A" and "yes" or "no").isEqualTo("yes")
Assertions.assertThat("" and "yes" or "no").isEqualTo("no")
Assertions.assertThat(1 and "yes" or "no").isEqualTo("yes")
Assertions.assertThat(0 and "yes" or "no").isEqualTo("no")
Assertions.assertThat(Date() and "yes" or "no").isEqualTo("yes")
@Suppress("CAST_NEVER_SUCCEEDS")
Assertions.assertThat(null as Date? and "yes" or "no").isEqualTo("no")
}
}
infix fun <E> Boolean?.and(other: E?): E? = if (this == true) other else null
infix fun <E> CharSequence?.and(other: E?): E? = if (!(this ?: "").isEmpty()) other else null
infix fun <E> Number?.and(other: E?): E? = if (this?.toInt() ?: 0 != 0) other else null
infix fun <E> Any?.and(other: E?): E? = if (this != null) other else null
infix fun <E> E?.or(other: E?): E? = this ?: other
正如德鲁·诺克斯引用的,kotlin使用if语句作为表达式, 所以三元条件运算符不再是必要的,
但是使用扩展函数和中缀重载,你可以自己实现,这里有一个例子
infix fun <T> Boolean.then(value: T?) = TernaryExpression(this, value)
class TernaryExpression<out T>(val flag: Boolean, val truly: T?) {
infix fun <T> or(falsy: T?) = if (flag) truly else falsy
}
然后像这样使用它
val grade = 90
val clazz = (grade > 80) then "A" or "B"
例如:var energy: Int = data?.get(position)?.energy?.toInt() ?: 0
在kotlin中,如果你使用?:,它会像这样工作,如果语句将返回null,那么?:0,它将取0或任何你写在这一边的东西。