2016-11-25 20 views
1

Kotlin有一个扩展功能run在Kotlin中使用运行函数而不是返回是否是一种好的做法?

/** 
* 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 
} 

哪种风格更好?

回答

5

对于更复杂的功能,第一个选项将更具可读性。 对于简单的功能,我建议看看Single-expression function的语法。

fun plus(a: Int, b: Int): Int = a + b 
相关问题