结论:
先执行 apply中的代码,然后返回 对象。
实验代码1:
import org.junit.Test
class MyTestUnit {
private var num = 1
@Test
fun t1() {
print(a(666).num)
}
fun a(n: Int) = this.apply { num = n } //先执行了 apply 里的代码,后返回了 this
}
运行结果截图1:
实验代码2:
import org.junit.Test
class MyTestUnit {
@Test
fun t2() {
print(b(888).num)
}
fun b(n: Int): Obj {
val obj = Obj(1)
return obj.apply { //先执行了 apply 里的代码,后返回了 this
this.num = n
}
}
}
data class Obj(var num: Int)
运行结果截图2: