Simple way to introduce a new scope


#1

I want to declare a block. Something like

let result = {
  val x1 = "x1"
  val x2 = "x2"
  x1 + x2
}

Please note, that I don’t want a lambda, I just want a block to scope some variables. Something like “let” in Lisp and other functional languages.

Now I’m doing it using:

let result = Unit.let {
  val x1 = "x1"
  val x2 = "x2"
  x1 + x2
}

It works, but seems a little bit strange. Is there any better way to do it?


#2

You can do:

val result = run {
  val x1 = "x1"
  val x2 = "x2"
  x1 + x2
}

Since the lambda is inlined, there is no performance penalty.

Alternatively:

val result = 
  "x1".let { x1 ->
    "x2".let { x2 ->
      x1 + x2
    }
  }

#3

Yes, run is exactly what I was looking for, thanks!