Kotlin 非空赋值的惯用方法
我想做到这一点:Kotlin 非空赋值的惯用方法,kotlin,Kotlin,我想做到这一点: val foo = if (getNullableValue() != null) getNullableValue() else computeDefaultValue() 我不喜欢的是重复使用getNullableValue()。为了消除重复,我想出了一个办法: val foo = getNullableValue()?.also{}?: run { computeDefaultValue() } 但不确定这是否是惯用语。IDE也会警告的空主体。有没有更好的方法来实现这
val foo = if (getNullableValue() != null) getNullableValue() else computeDefaultValue()
我不喜欢的是重复使用getNullableValue()
。为了消除重复,我想出了一个办法:
val foo = getNullableValue()?.also{}?: run { computeDefaultValue() }
但不确定这是否是惯用语。IDE也会警告
的空主体。有没有更好的方法来实现这一点?这就是Elvis操作员的作用:
val foo = getNullableValue() ?: computeDefaultValue()
例如:
fun getNullableValue1(): Int? {
return null
}
fun getNullableValue2(): Int? {
return 22
}
fun computeDefaultValue(): Int {
return 44
}
println(getNullableValue1() ?: computeDefaultValue())
println(getNullableValue2() ?: computeDefaultValue())
结果:
44
22
这就是Elvis操作员的作用:
val foo = getNullableValue() ?: computeDefaultValue()
例如:
fun getNullableValue1(): Int? {
return null
}
fun getNullableValue2(): Int? {
return 22
}
fun computeDefaultValue(): Int {
return 44
}
println(getNullableValue1() ?: computeDefaultValue())
println(getNullableValue2() ?: computeDefaultValue())
结果:
44
22