在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
对于我自己,我使用以下扩展函数:
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() }
就我个人而言,上面的代码比结构内联更具可读性
其他回答
when替换c类语言的切换操作符。最简单的形式是这样的
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
在Kotlin中没有三元运算符。乍一看,这似乎有问题。但是我们可以用内联if else语句因为这是表达式。我们要做的就是
var number = if(n>0) "Positive" else "Negetive"
这里我们可以用else if来阻塞我们需要的太多。像- - - - - -
var number = if(n>0) "Positive" else if(n<0) "Negative" else "Zero"
这一行比三元运算符简单易读。当我们在Java中使用多个三元运算符时,这看起来很可怕。但是这里我们有一个清晰的语法。甚至我们也可以把它写成多行。
这里的其他答案,例如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上某项内容的方法。
在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
另一种简单的方法
val value : String = "Kotlin"
value ?: ""
这里kotlin本身检查空值,如果它为空,则传递空字符串值。