let
首先let()的定義是這樣的,默認(rèn)當(dāng)前這個(gè)對(duì)象作為閉包的it參數(shù),返回值是函數(shù)里面最后一行,或者指定return
代碼示例:
fun testLet(): Int {
// fun <T, R> T.let(f: (T) -> R): R { f(this)}
"testLet".let {
println(it)
println(it)
println(it)
return 1
}
}
//運(yùn)行結(jié)果
//testLet
//testLet
//testLet
apply
apply函數(shù)是這樣的,調(diào)用某對(duì)象的apply函數(shù),在函數(shù)范圍內(nèi),可以任意調(diào)用該對(duì)象的任意方法,并返回該對(duì)象
代碼示例:
fun testApply() {
// fun <T> T.apply(f: T.() -> Unit): T { f(); return this }
ArrayList<String>().apply {
add("testApply")
add("testApply")
add("testApply")
println("this = " + this)
}.let { println(it) }
}
// 運(yùn)行結(jié)果
// this = [testApply, testApply, testApply]
// [testApply, testApply, testApply]
with
with函數(shù)是一個(gè)單獨(dú)的函數(shù),并不是Kotlin中的extension,所以調(diào)用方式有點(diǎn)不一樣,返回是最后一行,然后可以直接調(diào)用對(duì)象的方法,感覺像是let和apply的結(jié)合。
代碼示例:
fun testWith() {
// fun <T, R> with(receiver: T, f: T.() -> R): R = receiver.f()
with(ArrayList<String>()) {
add("testWith")
add("testWith")
add("testWith")
println("this = " + this)
}.let { println(it) }
}
// 運(yùn)行結(jié)果
// this = [testWith, testWith, testWith]
// kotlin.Unit
run
run函數(shù)和apply函數(shù)很像,只不過run函數(shù)是使用最后一行的返回,apply返回當(dāng)前自己的對(duì)象。
代碼示例:
fun testRun() {
// fun <T, R> T.run(f: T.() -> R): R = f()
"testRun".run {
println("this = " + this)
}.let { println(it) }
}
// 運(yùn)行結(jié)果
// this = testRun
// kotlin.Unit