在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
when替换c类语言的切换操作符。最简单的形式是这样的
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
其他回答
在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中以多种方式实现它
如果使用 如果(a) b else c 使用时 当(a) { True ->打印("value b") 错误->打印("value c") Else -> { 打印("在任何其他情况下默认返回") } } 空安全 Val a = b ?: c
使用以下中缀函数,我可以覆盖许多常见的用例,几乎与在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中没有三元操作,但是有一些有趣的方法可以解决这个问题。正如其他人指出的那样,直接翻译成Kotlin应该是这样的:
val x = if (condition) result1 else result2
但就我个人而言,我认为这可能会有点混乱,很难阅读。库中还内置了一些其他选项。你可以将takeIf{}与elvis操作符一起使用:
val x = result1.takeIf { condition } ?: result2
这里发生的事情是takeIf{}命令返回result1或null,而elvis操作符处理null选项。还有一些额外的选项,例如takeUnless {}:
val x = result1.takeUnless { condition } ?: result2
语言很清楚,你知道它在做什么。
如果这是一个常用的条件,您还可以做一些有趣的事情,比如使用内联扩展方法。让我们假设我们想要追踪一个Int类型的游戏分数,并且我们想要在给定条件不满足时总是返回0:
inline fun Int.zeroIfFalse(func: () -> Boolean) : Int = if (!func.invoke()) 0 else this
好吧,这看起来很难看。但是考虑一下它在使用时的样子:
var score = 0
val twoPointer = 2
val threePointer = 3
score += twoPointer.zeroIfFalse { scoreCondition }
score += threePointer.zeroIfFalse { scoreCondition }
如您所见,Kotlin在选择如何表达代码方面提供了很大的灵活性。我的例子有无数的变化,可能我还没有发现的方法。我希望这能有所帮助!
其他答案中没有提到的一些极端情况。
自从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。