kotlin作用域函數(shù)let/with/run/apply/also

函數(shù)調(diào)用 內(nèi)部訪問 返回值
obj?.let it 最后一行
obj?.also it 對(duì)象本身
obj?.run this 最后一行
obj?.apply this 對(duì)象本身
with(obj) this 最后一行

let

常用語(yǔ)非空判斷,【it】增加代碼可讀性

object?.let {
    setText(it.objText)
    setBackgroundColor(it.objColor)
}

also

常用語(yǔ)非空判斷,【it】增加代碼可讀性,適合鏈?zhǔn)秸{(diào)用

var object?.also{
    setText(it.objText)
    setBackgroundColor(it.objColor)
}.also{
    ...doSomething(it.objParam)
}

run

適合初始化并設(shè)置多條屬性,不需要返回值,例如:

findViewById<RecyclerView>(R.id.recycler).run {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = listAdapter
            addItemDecoration(DividerItemDecoration(this@MainActivity, LinearLayout.VERTICAL))
        }

apply

適合初始化并設(shè)置多條屬性并返回自身對(duì)象,例如:

private val paint = Paint().apply {
        isAntiAlias = false
        style = Paint.Style.STROKE
        color = getContext().getColor(R.color.colorAccent)
        strokeWidth = 4f.dp2px()
    }

with

val result:Int = with(supportData) {
            showInfo()
            spvTotal
        }
        with(supportDataNullAble) {
            this?.showInfo()
        }
最后編輯于
?著作權(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)容