在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
这里的其他答案,例如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上某项内容的方法。
其他回答
你可以这样做:
val ans = (exp1 == exp2) then "yes" ?: "no"
通过使用这个扩展:
infix fun<T> Boolean.then(first: T): T? = if (this) first else null
附注:先不要修改上面的中缀函数接受:T?,表达式就会变得逻辑错误。例:如果你先修改它接受空值:T?,那么val ans = (true == true)那么null ?: "abcd", ans将是"abcd",这将是不正确的。
when替换c类语言的切换操作符。最简单的形式是这样的
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
你可以使用var a= if (a) b else c来代替三元运算符。
kotlin的另一个好概念是Elvis运算符。你不需要每次都检查null。
val l = b?.length ?: -1
如果b不为空,则返回length,否则执行右边语句。
在使用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
}
对于我自己,我使用以下扩展函数:
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() }
就我个人而言,上面的代码比结构内联更具可读性