代码:
kotlin
fun main() {
var a = 1
var b = 2
a = b.apply {
b = a
println("$b")
println("$this")
}
println("$a $b")
}
打印结果:
1
2
2 1
原理分析:
kotlin
/**
* Calls the specified function [block] with `this` value as its receiver and returns `this` value.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#apply).
*/
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
我们看到apply 返回的this 其实就不是b了
所以b虽然在block() 里面被改了值 但是最后赋值给a 的是this
太棒了 交换两个数 不用temp变量去做中间容器了