這幾個(gè)都是 Standard.kt 中的高階函數(shù),使用起來比較相似,容易混淆,下面就分析一下它們的區(qū)別和使用場景。
先看下不使用這些高階函數(shù)的例子:
data class Person(val name: String, val age: Int) {
fun work(): String {
println("${name}正在工作...")
return "工作完成"
}
}
fun findPerson(): Person? {
return Person("JamFF", 18)
}
fun main() {
val person = findPerson()
println(person?.name) // 輸出 JamFF
println(person?.age) // 輸出 18
val result = person?.work() // 輸出 JamFF正在工作...
println(result) // 輸出 工作完成
}
一、let 函數(shù)
/**
* Calls the specified function [block] with `this` value as its argument and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#let).
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
使用 let 簡化:
fun main() {
val result = findPerson()?.let { person ->
println(person.name) // 輸出 JamFF
println(person.age) // 輸出 18
person.work() // 輸出 JamFF正在工作...
}
println(result) // 輸出 工作完成
Lambda 還可以簡化,使用 it 代替:
fun main() {
val result = findPerson()?.let {
println(it.name) // 輸出 JamFF
println(it.age) // 輸出 18
it.work() // 輸出 JamFF正在工作...
}
println(result) // 輸出 工作完成
}
在作用域中使用 it 代替調(diào)用者,最后一行為返回值。
二、run 函數(shù)
/**
* Calls the specified function [block] with `this` value as its receiver and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#run).
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
對于 T.() -> R 類型不理解的可以看這里:帶有接收者的函數(shù)字面值。
使用 run 簡化:
fun main() {
val result = findPerson()?.run {
println(this.name) // 輸出 JamFF
println(age) // 輸出 18
work() // 輸出 JamFF正在工作...
}
println(result) // 輸出 工作完成
}
在作用域中使用 this 代替調(diào)用者(可以省略),最后一行為返回值。
還有一個(gè)重載 run 函數(shù):
/**
* Calls the specified function [block] and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#run).
*/
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
該函數(shù)使用場景不多,看下面一個(gè)例子:
fun foo() {
val age = 42
val result = run {
val age = 8
println("內(nèi)部運(yùn)行年齡 $age")// 輸出 內(nèi)部運(yùn)行年齡 8
"內(nèi)部運(yùn)行結(jié)束"http:// 最后一行返回值
}
println(result)// 內(nèi)部運(yùn)行結(jié)束
println("外部運(yùn)行年齡 $age")// 輸出 外部運(yùn)行年齡 42
}
可以看到 run 函數(shù)新建了一個(gè)作用域,屏蔽了外面 age 變量, 另外 run 函數(shù)是有返回值的。
三、with 函數(shù)
/**
* Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#with).
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}
使用 with 簡化:
fun main() {
val result = with(findPerson()) {
println(this?.name) // 輸出 JamFF
println(this?.age) // 輸出 18
this?.work() // 輸出 JamFF正在工作...
}
println(result) // 輸出 工作完成
}
需要傳入?yún)?shù),在作用域中使用 this 代替參數(shù)(可以省略),最后一行為返回值。
四、apply 函數(shù)
/**
* Calls the specified function [block] with `this` value as its receiver and returns `this` value.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#apply).
*/
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
使用 apply 簡化:
fun main() {
val result = findPerson()?.apply {
println(this.name) // 輸出 JamFF
println(age) // 輸出 18
work() // 輸出 JamFF正在工作...
}
println(result) // 輸出 Person1(name=JamFF, age=18)
}
類似 run,區(qū)別是,返回值是調(diào)用者自己。
在作用域中使用 this 代替調(diào)用者(可以省略),調(diào)用者為返回值。
五、also 函數(shù)
/**
* Calls the specified function [block] with `this` value as its argument and returns `this` value.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#also).
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block(this)
return this
}
使用 also 簡化:
fun main() {
val result = findPerson()?.also {
println(it.name) // 輸出 JamFF
println(it.age) // 輸出 18
it.work() // 輸出 JamFF正在工作...
}
println(result) // 輸出 Person1(name=JamFF, age=18)
}
類似 let,區(qū)別是,返回值是調(diào)用者自己。
在作用域中使用 it 代替調(diào)用者,調(diào)用者為返回值。
六、 總結(jié)
上面五個(gè)函數(shù),不論用哪個(gè),都可以完成類似功能,只不過使用恰當(dāng)?shù)暮瘮?shù),可以進(jìn)一步減少代碼量,選擇標(biāo)準(zhǔn)可以參考下面圖片:

let、run、with、apply、also 如何選擇
最后再看下老外整理的兩張圖加深記憶:

Kotlin 標(biāo)準(zhǔn)方法流程圖

Kotlin 標(biāo)準(zhǔn)方法表格