简体   繁体   English

Kotlin函数类型在运行时的Java类型是什么?

[英]What is the Java type at runtime for a Kotlin function type?

If I have the Kotlin method bellow and call it from Java, what is the return type that I get in Java? 如果我有下面的Kotlin方法并从Java调用它,我在Java中得到的返回类型是什么?

fun ff(): (Int, Int) -> Int {
    return { x, y -> x + y }
}

The Kotlin function types (T1, ..., TN) -> R are represented by the FunctionN<T1, ..., TN, R> types of the Kotlin runtime. Kotlin函数类型(T1, ..., TN) -> R由Kotlin运行时的FunctionN<T1, ..., TN, R>类型表示。

There is a specification document describing this aspect of the language design at its current state. 有一个规范文档描述了语言设计在当前状态下的这一方面。

It says, in particular, that there are 23 function types from Function0 to Function22 in the Kotlin runtime for JVM (shipped as the kotlin-runtime library), looking like this: 它特别指出,在JVM的Kotlin运行时中,从Function0Function22有23种函数类型(作为kotlin-runtime库提供),如下所示:

package kotlin.jvm.functions

interface Function1<in P1, out R> : kotlin.Function<R> {
    fun invoke(p1: P1): R
}

The extension function types TR.(T1, ..., TN) -> R have the same runtime representation as normal functional types with the receiver prepended to the parameters list, namely (TR, T1, ..., TN) -> R . 扩展功能类型TR.(T1, ..., TN) -> R具有与正常功能类型相同的运行时表示形式,其中接收器位于参数列表的前面,即(TR, T1, ..., TN) -> R

Functions with more than 22 parameters are represented at runtime by a single type: 具有22个以上参数的函数在运行时用一种类型表示:

package kotlin.jvm.functions

interface FunctionN<out R> : kotlin.Function<R> {
    val arity: Int
    fun invokeVararg(vararg p: Any?): R
}

In Kotlin/JS, functional values are represented in the way that is natural to JS, ie they are compiled to a function definition and a reference to it: 在Kotlin / JS中,函数值以JS固有的方式表示,即它们被编译为函数定义和对其的引用:

function main$lambda(s1, s2) {
    println(s1 + s2);
    return Unit;
}

function main(args) {
    var f = main$lambda;
    /* ... */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM