在Kotlin中使用run函数而不是return是不是很好?
Kotlin有一个扩展功能run
。
/** * Calls the specified function [block] and returns its result. */ @kotlin.internal.InlineOnly public inline fun <R> run(block: () -> R): R = block()
而run
函数可以用来代替返回。
// 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 }
哪种风格更好?
对于更复杂的功能,第一个选项将更具可读性。 对于简单的函数,我会建议看看单表达式函数语法。
fun plus(a: Int, b: Int): Int = a + b