在Kotlin中评估代码块(以将变量隐藏在范围内)

use*_*643 3 kotlin

在Scala中,您可以编写

val x = {
  ... do some complex computations ..
  42
}
Run Code Online (Sandbox Code Playgroud)

将东西隐藏在代码块中。

我最接近科特林的是:

val x = {
  ... do some complex computations ..
  42
}()
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

编辑:

  • 不是run {}在上述例子本质上是相同
  • 通话费用昂贵吗?

回答:

  • 使用内run {}联,{}()但不使用内联(请参阅下面的我自己的答案)

mar*_*ran 5

使用run功能。它使用一个函数作为参数,运行它并返回结果。

val x = run {
  ... do some complex computations ..
  42
}
Run Code Online (Sandbox Code Playgroud)

run函数是内联的,因此不会有性能开销。