在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
看看这些文件:
在Kotlin中,if是一个表达式,即它返回一个值。因此, 没有三元运算符(条件?然后:else), 因为普通的if在这个角色中很管用。
其他回答
使用以下中缀函数,我可以覆盖许多常见的用例,几乎与在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 else语句因为这是表达式。我们要做的就是
var number = if(n>0) "Positive" else "Negetive"
这里我们可以用else if来阻塞我们需要的太多。像- - - - - -
var number = if(n>0) "Positive" else if(n<0) "Negative" else "Zero"
这一行比三元运算符简单易读。当我们在Java中使用多个三元运算符时,这看起来很可怕。但是这里我们有一个清晰的语法。甚至我们也可以把它写成多行。
when替换c类语言的切换操作符。最简单的形式是这样的
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
在使用apply()时,let在处理三元操作时似乎非常方便,因为它更优雅,并为您提供了空间
val columns: List<String> = ...
val band = Band().apply {
name = columns[0]
album = columns[1]
year = columns[2].takeIf { it.isNotEmpty() }?.let { it.toInt() } ?: 0
}
另一个有趣的方法是在以下情况使用:
when(a) {
true -> b
false -> c
}
在一些更复杂的场景中非常方便。老实说,这对我来说比……其他的……