在Kotlin中使用run函数而不是return是一种好习惯吗?

mmo*_*iro 1 return kotlin

Kotlin具有扩展功能run.

/**
 * Calls the specified function [block] and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R = block()
Run Code Online (Sandbox Code Playgroud)

并且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
}
Run Code Online (Sandbox Code Playgroud)

哪种款式更好?

Jan*_*son 5

对于更复杂的功能,第一个选项将更具可读性.对于简单的函数,我建议看看单表达式函数语法.

fun plus(a: Int, b: Int): Int = a + b
Run Code Online (Sandbox Code Playgroud)