Jim*_*Jim 3 kotlin kotlin-null-safety
在Kotlin中,还有其他的“ Kotlin”方法可以执行以下操作吗?
fun parse(inputSample: Sample): List<String> =
when {
inputSample.foo != null -> parse(inputSample.foo)
inputSample.bar != null -> parse(inputSample.bar)
else -> emptyList()
}
Run Code Online (Sandbox Code Playgroud)
我怀疑nullwith的支票when可以用Kotlin写成不同的形式
You can use scoping function to reduce "redundant" code:
fun parse(inputSample: Sample): List<String> = inputSample.run {
when {
foo != null -> parse(foo)
bar != null -> parse(bar)
else -> emptyList()
}
}
Run Code Online (Sandbox Code Playgroud)
或与elvis运算符组合(请注意,这是假定的foo并且bar属于同一类型):
fun parse(inputSample : Sample) : List<String> = inputSample.run {
(foo ?: bar)?.let { parse(it) } ?: emptyList()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |