Kotlin invoke 函数调用重载

Kotlin 允许对 方法调用 () 运算符重载,对于实现 operator fun invoke(...) 重载的,可通过实例名直接调用。

比如 a() 则会转换成 a.invoke()

根据参数数量 匹配对应重载的 invoke(...) 函数,集合 都可以重载。

1. invoke运算符重载

语法:

kotlin 复制代码
operator fun invoke() {
	...
}

举例:

kotlin 复制代码
class Add(private val a: Int) {
    operator fun invoke(b: Int): Int = a + b
}

fun main() {
    val add5 = Add(5)
    println(add5(3)) // 输出 8
}
2. invoke 也可用于扩展函数

格式为:operator Type.invoke(xx)

举例:

kotlin 复制代码
operator fun Int.invoke(a: Int, b: Int): Int {
    return this + a + b
}

fun main() {
    val a = 10
    println(a(10, 10))
}

输出:30

3. Function0 ... Function22, FunctionN 函数

对于 Kotlin 匿名的 lambda 函数 ,实际也是 实现 invoke 方法,都是基于 kotlin.jvm.functions 包下 Function* 接口 实现。

包含 Function 0 - 22FunctionN 的接口。

查看 Function2 源码,只是声明了 operator fun invoke 方法:

kotlin 复制代码
/** A function that takes 2 arguments. */
public interface Function2<in P1, in P2, out R> : Function<R> {
    /** Invokes the function with the specified arguments. */
    public operator fun invoke(p1: P1, p2: P2): R
}

相关的 lambda 函数,编译后,就是 实现 Function 接口 invoke 函数。

文档

相关推荐
阿巴斯甜18 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker19 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq952720 小时前
Andorid Google 登录接入文档
android
黄林晴21 小时前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab1 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿2 天前
Android MediaPlayer 笔记
android
Jony_2 天前
Android 启动优化方案
android
阿巴斯甜2 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇2 天前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_2 天前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android