在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
如果你不知道如何使用标准符号,你也可以使用类似这样的中缀来创建/模拟它:
创建一个类来保存目标和结果:
data class Ternary<T>(val target: T, val result: Boolean)
创建一些中缀函数来模拟三元操作
infix fun <T> Boolean.then(target: T): Ternary<T> {
return Ternary(target, this)
}
infix fun <T> Ternary<T>.or(target: T): T {
return if (this.result) this.target else target
}
然后你就可以这样使用它了:
val collection: List<Int> = mutableListOf(1, 2, 3, 4)
var exampleOne = collection.isEmpty() then "yes" or "no"
var exampleTwo = (collection.isNotEmpty() && collection.contains(2)) then "yes" or "no"
var exampleThree = collection.contains(1) then "yes" or "no"
其他回答
在Kotlin中,你可以像这样使用三元运算:"add b" else "add 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使用if语句作为表达式, 所以三元条件运算符不再是必要的,
但是使用扩展函数和中缀重载,你可以自己实现,这里有一个例子
infix fun <T> Boolean.then(value: T?) = TernaryExpression(this, value)
class TernaryExpression<out T>(val flag: Boolean, val truly: T?) {
infix fun <T> or(falsy: T?) = if (flag) truly else falsy
}
然后像这样使用它
val grade = 90
val clazz = (grade > 80) then "A" or "B"
为什么要用这样的东西:
when(a) {
true -> b
false -> b
}
当你实际上可以使用这样的东西(在这种情况下,a是布尔值):
when {
a -> b
else -> b
}
(x:Int,y:Int):字符串= if (x>y)"max = $x" else "max = $y"
内联funcation