I am really not sure how to name the title, hence I am going to explain it as best as I can:
val a = b ?: ({
val temp = c.evaluate()
store(temp)
temp // returns temp to the lambda, which will set `a` to `temp` if `b` is null
})()
1: what works, what I currently use
This works fine, but what I ideally want to do is just using the code block and not passing the lambda to a function (({})
) and then evaluating it. In my imagination, it would look something like this:
val a = b ?: {
val temp = c.evaluate()
store(temp)
temp // returns temp to the lambda, which will set `a` to `temp` if `b` is null
}
2: what I would like to have
The above does not work. I am actually just looking for a better way to write 1.
Elvis Operator (?:)It is used to return the not null value even the conditional expression is null. It is also used to check the null safety of values. In some cases, we can declare a variable which can hold a null reference.
In certain computer programming languages, the Elvis operator, often written ?: , is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand.
You can use the run
function:
val a = b ?: run {
val temp = c.evaluate()
store(temp)
temp
}
You can use the also
function:
val a = b ?: c.evaluate().also { store(it) }
This allows you to do something with a value while passing that value as the result of the also
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