函數(shù)調(diào)用 | 內(nèi)部訪問 | 返回值 |
---|---|---|
obj?.let | it | 最后一行 |
obj?.also | it | 對(duì)象本身 |
obj?.run | this | 最后一行 |
obj?.apply | this | 對(duì)象本身 |
with(obj) | this | 最后一行 |
let
常用語非空判斷,【it】增加代碼可讀性
object?.let {
setText(it.objText)
setBackgroundColor(it.objColor)
}
also
常用語非空判斷心俗,【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()
}