Assign value to variable only if is not null - Kotlin
The operator is called Elvis Operator. It evaluates if x
is not null and if that's true, assigns x
to y
. If it is null, it evaluates the statement after the question mark, returning immediately and therefore leaving y
untouched.
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
.