[英]Kotlin: how to return some value from scope?
In Scala I can write something like this: 在Scala中我可以这样写:
val something = {
val temp1 = ...
val temp2 = ...
temp1 + temp2
}
As far as I know the best way to do the same in Kotlin is: 据我所知,在Kotlin做同样的事情的最佳方法是:
val something = {
val temp1 = ...
val temp2 = ...
temp1 + temp2
}()
Actually it's a lambda with type Unit -> Int which is called immediately. 实际上它是一个类型为Unit - > Int的lambda,它会被立即调用。 I wonder could this code be improved somehow?
我想知道这个代码能以某种方式改进吗? Maybe there is a built in function which allows me to write val something = block { ... } or something like this?
也许有一个内置函数,它允许我写val something = block {...}或类似的东西?
You can use function run
, like: 您可以使用函数
run
,如:
val something = run {
val temp1 = ...
val temp2 = ...
temp1 + temp2
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.