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 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
android·运维·网络·人工智能·学习·安全·macos
YM52e1 天前
鸿蒙Flutter Padding内边距:EdgeInsets详解
android·学习·flutter·华为·harmonyos·鸿蒙
牛奔1 天前
Go 如何打印调试深层或嵌套的结构体
开发语言·后端·golang
geovindu1 天前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
学逆向的1 天前
汇编——JCC指令
开发语言·汇编·网络安全
mayaairi1 天前
JS循环语句深度解析:嵌套for、while与do...while
开发语言·前端·javascript
kite01211 天前
Go语言Map深度解析与最佳实践
开发语言·后端·golang
Rex叶然1 天前
ScreenMatch适配安卓屏幕脚本,用于老项目
android·screenmatch·安卓屏幕适配
阿pin1 天前
Android随笔-Activity启动流程深度分析
android·activity启动流程
l156469481 天前
突围!图文混合知识库难以解析,Kimi-K3 原生视觉架构深耕知识工作,DMXAPI 统一接口,缩短项目开发周期
java·大数据·开发语言