Kotlin之let,apply,with,run函數(shù)區(qū)別

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

Kotlin之let,apply,with,run函數(shù)區(qū)別

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容