1、概述
除了 ?.let 在作为安全可控性的时候好用外,with,apply 也是使用频率很高的。其中 apply 尤其好用。 在java 代码中想要链式编程,设置一个对象的属性时,往往跑到这个属性去把该set方法返回this,方便编程。或者更规范的另外建个 builder。然而在kotlin 里用apply 就可以了
2、with 函数
with 函数把第一个参数,作为lambda(第二个参数) 的接收者,可以用this访问,也可以省略 this。
//本质是一个内联函数,第一个参数是目标对象,第二个参数是lambda. 返回值是lambda的返回值
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}
示例:
fun testWith() {
val strBuilder = StringBuilder()
val reval = with(strBuilder) {
append("1")
append("➕")
append("2")
this.toString()
}
println(reval)
}
3、apply
apply的功能和with类似,但是更方便。直接作为对象的方法函数,返回值为对象本身
//是扩展函数(也是内联),参数为lambda表达式。返回值为该对象自己
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
示例:
fun testApply() {
val strBuilder = StringBuilder()
println(strBuilder.apply {
append("1")
append("➕")
append("2")
}.toString())
}