with 傳參可以是任意對象睡汹,上下文為this,返回值為最后一行的結(jié)果
val withResult = with(StringBuffer()) {
println("start")
append("hello")
append(" ")
append("world")
println("end")
toString()
}
println(withResult)
run 任意對象調(diào)用寂殉,上下文為this囚巴,返回值為最后一行的結(jié)果
val runResult = StringBuffer().run {
println("start")
append("hello")
append(" ")
append("world")
println("end")
toString()
}
println(runResult)
apply 任意對象調(diào)用,上下文為this,返回值為對象本身
val applyResult = StringBuffer().apply {
println("start")
append("hello")
append(" ")
append("world")
println("end")
}
println(applyResult.toString())
let 任意對象調(diào)用文兢,上下文為it晤斩,返回值為最后一行結(jié)果
val letResult = StringBuffer().let {
println("start")
it.append("hello")
it.append(" ")
it.append("world")
println("end")
it.toString()
}
println(letResult)
以上不同寫法運行結(jié)果一致:
start
end
hello world
also 任意對象調(diào)用焕檬,上下文為it姆坚,返回值為最后一行結(jié)果
val alsoResult = StringBuffer().also {
println("start")
it.append("hello")
it.append(" ")
it.append("world")
println("end")
}
println(alsoResult.toString())
以上不同寫法運行結(jié)果一致:
start
end
hello world
run、apply实愚、let 兼呵、also都支持鏈式調(diào)用
StringBuffer().run{ }.run{ }
StringBuffer().apply{ }.apply{ }
StringBuffer().let{ }.let{ }
StringBuffer().also{ }.also{ }
標準函數(shù) | 調(diào)用方式 | 上下文 | 返回值 |
---|---|---|---|
with | 任意對象參數(shù)傳入 | this | 最后一行結(jié)果 |
run | 任意對象調(diào)用 | this | 最后一行結(jié)果 |
apply | 任意對象調(diào)用 | this | 對象本身 |
let | 任意對象調(diào)用 | it | 最后一行結(jié)果 |
also | 任意對象調(diào)用 | it | 對象本身 |