Kotlin has an extension function run
.
/**
* Calls the specified function [block] and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R = block()
And run
function can be used instead of return.
// an example multi-line method using return
fun plus(a: Int, b: Int): Int {
val sum = a + b
return sum
}
// uses run instead of return
fun plus(a: Int, b: Int): Int = run {
val sum = a + b
sum
}
Which style is better?
For more complicated functions the first option will be more readable. For simple functions I would suggest taking a look at Single-expression function syntax.
fun plus(a: Int, b: Int): Int = a + b