Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute and Return from Code Block (after Elvis operator)

Tags:

kotlin

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.

like image 716
creativecreatorormaybenot Avatar asked Dec 02 '18 15:12

creativecreatorormaybenot


People also ask

When to use Elvis operator?

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.

What is Elvis operator in java?

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.


2 Answers

You can use the run function:

val a = b ?: run {
    val temp = c.evaluate()
    store(temp)
    temp
}
like image 161
Minn Avatar answered Sep 29 '22 11:09

Minn


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

like image 29
Erwin Bolwidt Avatar answered Sep 29 '22 13:09

Erwin Bolwidt