Elvis operator right hand


#1

``

var b:Int?

Is there a way to remove the function call in there ?

{code}
val a = b ?: {
  b = 5
  3
}()

{code}

It seem we can’t write
``

{code}
val a = b ?: {
  b = 5
  3
}
{code}

#2

No, we don't have such ability.

  1. It’s pretty rare case.
  2. If we gave such ability, code would be very hard to comprehend. If you need complex Elvis expression, it is always better to use plain old if.   

#3

If I see what you mean correctly, you want some way to join a number of statements into one expression on the right-hand side of ?: Passing a single lambda does not work, because the type is wrong. You can do

b ?: run {   b = 5   3 }

This is faster due to inlining of run() and arguably more readable


#4

Yes, this is exactly what I wanted (an inlined construct that does the same as the if then construct while being more compact and readable)

It was really important to be inlined, because this work fine :

someCode()

and this :

execute the lambda {
someCode()
}

sometimes produces initializer errors (especially is someCode() uses objects)