问题
Is there an idiom in Kotlin for setting a variable to null if it is not already null? Something more semantically pleasing than:
var test: String? = null
if(test != null) test = null
回答1:
You can use the execute if not null idiom:
test?.let { test = null }
回答2:
Just assign null to local variable:
test = null
In case if it's not null - you assign null to this variable. In case if variable is null - you just assign null to it, so nothing changed.
回答3:
I came up with this extensions which makes this simpler:
inline fun <T, R> T.letThenNull(block: (T) -> R): T? { block(this); return null }
val test: Any? = null
...
test = test?.letThenNull { /* do something with test */ }
来源:https://stackoverflow.com/questions/39583928/kotlin-set-to-null-if-not-null