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
In an effort to rid the world of NullPointerException , variable types in Kotlin don't allow the assignment of null . If you need a variable that can be null, declare it nullable by adding ? at the end of its type. Declares a non- null String variable.
Nullable and Non-Nullable Types in Kotlin – Kotlin type system has distinguish two types of references that can hold null (nullable references) and those that can not (non-null references). A variable of type String can not hold null. If we try to assign null to the variable, it gives compiler error.
You can use the "?. let" operator in Kotlin to check if the value of a variable is NULL. It can only be used when we are sure that we are refereeing to a non-NULL able value.
Consequently, any variable cannot contain the null value unless you explicitly say it can. This way, you can avoid the danger of null references, and you do not have to wait for exceptions or errors to be thrown at runtime. Kotlin supports this possibility since its first release, and it is called null safety.
You can use the execute if not null idiom:
test?.let { test = null }
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.
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 */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With