Is there a clean way in Kotlin to assign a value to a variable only if the value is not null?
My example is:
if(x != null) y = x
I found a solution like
y = x? : return
but I don't understand if this does what I want and how this operator works.
Kotlin types system differentiates between references which can hold null (nullable reference) and which cannot hold null (non null reference). Normally,types of String are not nullable. To make string which holds null value, we have to explicitly define them by putting a ? behind the String as: String?
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.
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.
Another solution if You don't want to return from function just yet:
x?.let{ y = it }
Which checks if x
is non-null then passes it as the only parameter to the lambda block.
This is also a safe call in case your x
is a var
.
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