In Scala, you can write
val x = {
... do some complex computations ..
42
}
to hide stuff inside of the code block.
The closest I came in Kotlin is:
val x = {
... do some complex computations ..
42
}()
Is there a better way?
EDIT:
run {}
in the above example essentially the sameANSWER:
run {}
inlines, whereas {}()
does NOT (see my own answer below)Use the run
function. It takes a function as a parameter, runs it and returns the result.
val x = run {
... do some complex computations ..
42
}
The run
function is inlined, so it will have no performance overhead.
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