在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
在Kotlin中,你可以像这样使用三元运算:"add b" else "add c"
其他回答
对于我自己,我使用以下扩展函数:
fun T?.or<T>(default: T): T = if (this == null) default else this
fun T?.or<T>(compute: () -> T): T = if (this == null) compute() else this
第一个函数将在object = null的情况下返回提供的默认值。第二个将在相同情况下计算lambda中提供的表达式。
用法:
1) e?.getMessage().or("unknown")
2) obj?.lastMessage?.timestamp.or { Date() }
就我个人而言,上面的代码比结构内联更具可读性
其他答案中没有提到的一些极端情况。
自从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。
如果你不知道如何使用标准符号,你也可以使用类似这样的中缀来创建/模拟它:
创建一个类来保存目标和结果:
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"
另一个有趣的方法是在以下情况使用:
when(a) {
true -> b
false -> c
}
在一些更复杂的场景中非常方便。老实说,这对我来说比……其他的……
Java
int temp = a ? b : c;
相当于Kotlin:
var temp = if (a) b else c