在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
对于我自己,我使用以下扩展函数:
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() }
就我个人而言,上面的代码比结构内联更具可读性
其他回答
您可以在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
}
博士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三元条件运算符)所示,扩展还可以帮助解决您的用例。
为什么要用这样的东西:
when(a) {
true -> b
false -> b
}
当你实际上可以使用这样的东西(在这种情况下,a是布尔值):
when {
a -> b
else -> b
}
使用以下中缀函数,我可以覆盖许多常见的用例,几乎与在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
您可以定义自己的布尔扩展函数,当布尔值为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