函数调用 | 内部访问 | 返回值 |
---|---|---|
obj?.let | it | 最后一行 |
obj?.also | it | 对象本身 |
obj?.run | this | 最后一行 |
obj?.apply | this | 对象本身 |
with(obj) | this | 最后一行 |
let
常用语非空判断,【it】增加代码可读性
object?.let {
setText(it.objText)
setBackgroundColor(it.objColor)
}
also
常用语非空判断,【it】增加代码可读性,适合链式调用
var object?.also{
setText(it.objText)
setBackgroundColor(it.objColor)
}.also{
...doSomething(it.objParam)
}
run
适合初始化并设置多条属性,不需要返回值,例如:
findViewById<RecyclerView>(R.id.recycler).run {
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = listAdapter
addItemDecoration(DividerItemDecoration(this@MainActivity, LinearLayout.VERTICAL))
}
apply
适合初始化并设置多条属性并返回自身对象,例如:
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()
}