Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate code block in Kotlin (to hide variables inside scope)

Tags:

kotlin

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:

  • isn’t run {} in the above example essentially the same
  • is calling run costly?

ANSWER:

  • using run {} inlines, whereas {}() does NOT (see my own answer below)
like image 901
user3612643 Avatar asked Jan 27 '23 12:01

user3612643


1 Answers

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.

like image 143
marstran Avatar answered Feb 15 '23 23:02

marstran