已解决
Kotlin apply 交换两个数
来自网友在路上 176876提问 提问时间:2023-11-05 14:31:05阅读次数: 76
最佳答案 问答题库768位专家为你答疑解惑
代码:
fun main() {var a = 1var b = 2a = b.apply {b = aprintln("$b")println("$this")}println("$a $b")
}打印结果:
1
2
2 1
原理分析:
/*** 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变量去做中间容器了
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"Kotlin apply 交换两个数":http://eshow365.cn/6-32752-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!