with、run、apply、let、also 函數(shù)區(qū)別

with 傳參可以是任意對(duì)象,上下文為this,返回值為最后一行的結(jié)果

    val withResult = with(StringBuffer()) {
        println("start")
        append("hello")
        append(" ")
        append("world")
        println("end")
        toString()
    }
    println(withResult)

run 任意對(duì)象調(diào)用,上下文為this,返回值為最后一行的結(jié)果

 val runResult = StringBuffer().run {
        println("start")
        append("hello")
        append(" ")
        append("world")
        println("end")
        toString()
    }
    println(runResult)

apply 任意對(duì)象調(diào)用,上下文為this,返回值為對(duì)象本身

    val applyResult = StringBuffer().apply {
        println("start")
        append("hello")
        append(" ")
        append("world")
        println("end")
    }
    println(applyResult.toString())

let 任意對(duì)象調(diào)用,上下文為it,返回值為最后一行結(jié)果

 val letResult = StringBuffer().let {
        println("start")
        it.append("hello")
        it.append(" ")
        it.append("world")
        println("end")
        it.toString()
    }

    println(letResult)

以上不同寫法運(yùn)行結(jié)果一致:

start
end
hello world

also 任意對(duì)象調(diào)用,上下文為it,返回值為最后一行結(jié)果

     val alsoResult = StringBuffer().also {
        println("start")
        it.append("hello")
        it.append(" ")
        it.append("world")
        println("end")
    }

    println(alsoResult.toString())

以上不同寫法運(yùn)行結(jié)果一致:

start
end
hello world

run、apply、let 、also都支持鏈?zhǔn)秸{(diào)用

StringBuffer().run{  }.run{  }
StringBuffer().apply{  }.apply{  }
StringBuffer().let{  }.let{  }
StringBuffer().also{  }.also{  }
標(biāo)準(zhǔn)函數(shù) 調(diào)用方式 上下文 返回值
with 任意對(duì)象參數(shù)傳入 this 最后一行結(jié)果
run 任意對(duì)象調(diào)用 this 最后一行結(jié)果
apply 任意對(duì)象調(diào)用 this 對(duì)象本身
let 任意對(duì)象調(diào)用 it 最后一行結(jié)果
also 任意對(duì)象調(diào)用 it 對(duì)象本身
最后編輯于
?著作權(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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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