Kotlin: how to return some value from an area?

In Scala, I can write something like this:

val something = { val temp1 = ... val temp2 = ... temp1 + temp2 } 

As far as I know, the best way to do the same in Kotlin is:

 val something = { val temp1 = ... val temp2 = ... temp1 + temp2 }() 

This is actually a lambda with the type Unit → Int, which is called immediately. I wonder if this code can somehow improve? Maybe there is a built-in function that allows me to write val something = block {...} or something like this?

+6
source share
1 answer

You can use the run function, for example:

 val something = run { val temp1 = ... val temp2 = ... temp1 + temp2 } 
+13
source

Source: https://habr.com/ru/post/982379/


All Articles