Kotlin invoke 函数调用重载
Kotlin 允许对 方法调用 ()
运算符重载,对于实现 operator fun invoke(...)
重载的,可通过实例名直接调用。
比如 a()
则会转换成 a.invoke()
。
根据参数数量 匹配对应重载的 invoke(...)
函数,类和集合 都可以重载。
1. invoke运算符重载
语法:
operator fun invoke() {...
}
举例:
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)
举例:
operator fun Int.invoke(a: Int, b: Int): Int {return this + a + b
}fun main() {val a = 10println(a(10, 10))
}
输出:30
3. Function0 … Function22, FunctionN 函数
对于 Kotlin 匿名的 lambda
函数,实际也是 实现 invoke
方法,都是基于 kotlin.jvm.functions
包下 Function*
接口 实现。
包含 Function 0 - 22
和 FunctionN
的接口。
查看 Function2
源码,只是声明了 operator fun invoke
方法:
/** 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
函数。
文档
- invoke operator
- Invoking a function type instance
- Functions.kt