Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: how to return some value from scope?

Tags:

kotlin

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
}()

Actually it's a lambda with type Unit -> Int which is called immediately. 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?

like image 429
Aleksander Alekseev Avatar asked Feb 12 '15 12:02

Aleksander Alekseev


People also ask

How do I return a value from Kotlin?

To return values, we use the return keyword. In the example, we have two square functions. When a funcion has a body enclosed by curly brackets, it returns a value using the return keyword. The return keyword is not used for functions with expression bodies.

How do I return a value from a coroutine scope?

As mentioned in previous answer you can use withContext . Here is the small explaination from docs: Calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result.

What is Kotlin return@?

return@ is a statement in Kotlin which helps the developers to return a function to the called function. In simple words, return@ can return any value, anonymous function, simple inline function, or a lambda function.


1 Answers

You can use function run, like:

val something = run {
  val temp1 = ...
  val temp2 = ...
  temp1 + temp2
}
like image 95
bashor Avatar answered Oct 06 '22 16:10

bashor