Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 635 Vote(s) - 3.63 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Assign value to variable only if is not null - Kotlin

#1
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.
Reply

#2
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.

Reply

#3
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`.
Reply

#4
Your code is the exact same but with less writing as:

if(x != null)
y = x
else
return

When using the Elvis Operator it shortens the if else statement to:

y=x ?: return
If the left side is true (x is not null) then y will be assigned, else the right side will be executed.
Reply

#5
For those searching and want a solution that does **not** immediately return. You can hold your nose and do this:

`y = x ?: y`

As a good programmer I shudder to assign a variable to itself just to satisfy syntax. But that's kotlin for you! Those designers thought of everything!
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through