run 、 apply 、 let 、 also 和 with 五個函數均位於 kotlin 包下的 Standard 文件中,其含義和用法比較相似,現分別介紹如下。
run
用法1
函數定義:
public inline fun <R> run(block: () -> R): R = block()
功能:調用run函數塊。返回值為函數塊最后一行,或者指定return表達式。
示例:
val a = run {
println("run")
return@run 3
}
println(a)
運行結果:
run
3
用法2
函數定義:
public inline fun <T, R> T.run(block: T.() -> R): R = block()
功能:調用某對象的run函數,在函數塊內可以通過 this 指代該對象。返回值為函數塊的最后一行或指定return表達式。
示例:
val a = "string".run {
println(this)
3
}
println(a)
運行結果:
string
3
apply
函數定義:
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
功能:調用某對象的apply函數,在函數塊內可以通過 this 指代該對象。返回值為該對象自己。
示例:
val a = "string".apply {
println(this)
}
println(a)
運行結果:
string
string
let
函數定義:
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
功能:調用某對象的let函數,則該對象為函數的參數。在函數塊內可以通過 it 指代該對象。返回值為函數塊的最后一行或指定return表達式。
示例:
val a = "string".let {
println(it)
3
}
println(a)
運行結果:
string
3
also
函數定義(Kotlin1.1新增的):
public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }
功能:調用某對象的also函數,則該對象為函數的參數。在函數塊內可以通過 it 指代該對象。返回值為該對象自己。
示例:
val a = "string".also {
println(it)
}
println(a)
運行結果:
string
string
with
函數定義:
public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
功能:with函數和前面的幾個函數使用方式略有不同,因為它不是以擴展的形式存在的。它是將某對象作為函數的參數,在函數塊內可以通過 this 指代該對象。返回值為函數塊的最后一行或指定return表達式。
示例:
val a = with("string") {
println(this)
3
}
println(a)
運行結果:
string
3
參考資料
[What's New in Kotlin 1.1 - also(), takeIf() and takeUnless()](https://kotlinlang.org/docs/reference/whatsnew11.html#also-takeif-and-takeunless)