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?
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.
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.
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.
You can use function run
, like:
val something = run {
val temp1 = ...
val temp2 = ...
temp1 + temp2
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With