Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value to variable only if is not null - Kotlin

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.

like image 202
BlueSeph Avatar asked May 14 '18 21:05

BlueSeph


People also ask

How do you declare not null variable in Kotlin?

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?

How does Kotlin check not null?

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.

How do I assign a value to null in Kotlin?

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.


1 Answers

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.

like image 102
Pawel Avatar answered Oct 04 '22 11:10

Pawel