在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
在使用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
}
其他回答
在Kotlin中,你可以像这样使用三元运算:"add b" else "add c"
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
}
使用以下中缀函数,我可以覆盖许多常见的用例,几乎与在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
Java中等价的三元运算符
a ? b : c
是一个简单的IF在Kotlin一行
if(a) b else c
没有三元操作符(条件?然后:else),因为 普通的如果在这个角色中表现得很好。
https://kotlinlang.org/docs/reference/control-flow.html#if-expression
Null比较的特殊情况
你可以使用Elvis运算符
if ( a != null ) a else b
// equivalent to
a ?: b
在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