假设我们有以下代码:
class QuickExample {
fun function(argument: SomeOtherClass) {
if (argument.mutableProperty != null ) {
doSomething(argument.mutableProperty)
} else {
doOtherThing()
}
}
fun doSomething(argument: Object) {}
fun doOtherThing() {}
}
class SomeOtherClass {
var mutableProperty: Object? = null
}
与Java中不同的是,在Java中,您可能会在运行时担心空引用的取消,但这不会编译-这是非常正确的.当然,在‘if’中,一旦mutableProperty
不再为NULL.
My question is what's the best way to handle this?
A few options are apparent. Without using any new Kotlin language features, the simplest way is obviously to copy the value to a method-scope one that won't subsequently change.
There's this:
fun function(argument: SomeOtherClass) {
argument.mutableProperty?.let {
doSomething(it)
return
}
doOtherThing()
}
这有一个明显的缺点,即您需要提前返回或避免执行后续代码-在某些较小的上下文中可以,但有一些问题.
Then there's this possibility:
fun function(argument: SomeOtherClass) {
argument.mutableProperty.let {
when {
it != null -> {
doSomething(it)
}
else -> {
doOtherThing()
}
}
}
}
but whilst it has greater clarity of purpose, arguably it's more unwieldy and verbose than the Java-style way of dealing with this.
我遗漏了什么吗?有没有更好的习惯用法来实现这一点?