在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
这里的其他答案,例如takeIf假设x = (a != null) ?A: c或x = (A != null) ?a.method(): c,但这实际上并不等同于x = a ?B: c
实现一个真正等价的三元运算符与空安全检查(即x = (a != null) ?c)你可以用let代替takeIf。
Val x = a?让{b} ?: c
其中b可能是也可能不是调用a上某项内容的方法。
其他回答
其他答案中没有提到的一些极端情况。
自从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。
使用以下中缀函数,我可以覆盖许多常见的用例,几乎与在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
在kotlin中没有三元运算符,因为if else块返回值。
所以,你可以: Val Max = if (a > b) a else b 而不是java的Max = (a > b) ?B: c
我们也可以使用when construction,它也返回值:
val max = when(a > b) {
true -> a
false -> b
}
下面是kotlin文档的链接:Control Flow: if, when, for, while
记住,与许多流行语言不同,三元运算符和猫王运算符在Kotlin中具有不同的含义。表情干什么?在Kotlin编译器中value1: value2会给你不好的单词,不像任何其他语言,因为在Kotlin中没有三元运算符,就像官方文档中提到的那样。原因是if、when和try-catch语句本身返回值。
那么,做表情?Value1: value2可以替换为
Val Max = if (a > b) print(选择一个) 其他的 打印(“选择b”)
Kotlin拥有的Elvis运算符只适用于可空变量的情况,例如:
如果我执行类似value3 = value1 ?: value2这样的操作,那么如果value1为null,那么将返回value2,否则将返回value1。
从这些回答中可以得到更清晰的理解。