在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"
其他回答
例如:var energy: Int = data?.get(position)?.energy?.toInt() ?: 0
在kotlin中,如果你使用?:,它会像这样工作,如果语句将返回null,那么?:0,它将取0或任何你写在这一边的东西。
在Kotlin中没有三元运算符,最封闭的是下面两种情况,
If else作为表达式语句
val a = true if(a) print(" a是真")else print(" a是假")
猫王运营商
如果?:左边的表达式不为空,则猫王操作符 返回它,否则返回右边的表达式。请注意 右边的表达式只在左边的表达式被求值 Side为空。
val name = node.getName() ?: throw IllegalArgumentException("name expected")
参考文档
在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
您可以在Kotlin中使用if表达式。在Kotlin中if是一个带有结果值的表达式。所以在Kotlin中,我们可以写
fun max(a: Int, b: Int) = if (a > b) a else b
在Java中,我们可以用更大的代码实现同样的效果
int max(int a, int b) {
return a > b ? a : b
}
这里的其他答案,例如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上某项内容的方法。