Kotlin apply 交换两个数

代码:

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变量去做中间容器了

相关推荐
同学小张3 小时前
【端侧AI 与 C++】1. llama.cpp源码编译与本地运行
开发语言·c++·aigc·llama·agi·ai-native
踢球的打工仔4 小时前
PHP面向对象(7)
android·开发语言·php
汤姆yu6 小时前
基于python的外卖配送及数据分析系统
开发语言·python·外卖分析
Yue丶越6 小时前
【C语言】字符函数和字符串函数
c语言·开发语言·算法
翔云 OCR API6 小时前
人脸识别API开发者对接代码示例
开发语言·人工智能·python·计算机视觉·ocr
V***u4537 小时前
MS SQL Server partition by 函数实战二 编排考场人员
java·服务器·开发语言
这是程序猿7 小时前
基于java的ssm框架旅游在线平台
java·开发语言·spring boot·spring·旅游·旅游在线平台
芳草萋萋鹦鹉洲哦7 小时前
【elemen/js】阻塞UI线程导致的开关卡顿如何优化
开发语言·javascript·ui
爱学习的小邓同学7 小时前
C++ --- 多态
开发语言·c++
颜*鸣&空7 小时前
QT实现串口通信+VSPD+串口调试工具
开发语言·qt