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 函数。

文档

相关推荐
zh_xuan21 小时前
Android 传统view嵌入compose
android
FuckPatience1 天前
Visual Studio C# 项目中文件后缀简介
开发语言·c#
ZHANG13HAO1 天前
Android 13 AOSP 内置 NekoTTS 中文免费商用 TTS 完整流程
android
许杰小刀1 天前
ctfshow-web文件包含(web78-web86)
android·前端·android studio
014-code1 天前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
lly2024061 天前
组合模式(Composite Pattern)
开发语言
游乐码1 天前
c#泛型约束
开发语言·c#
Dontla1 天前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen1 天前
python rest请求、requests
开发语言·python
铁东博客1 天前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang