kotlin - 在 Kotlin 中扩展具有不同签名的 2 个 lambda

标签 kotlin

在 Kotlin 中,我们无法创建实现 2 个具有不同签名的 lambda 的类,如下所示:

class Test<T> : (T) -> Unit, () -> T {
    ...
}

给出以下错误:

Type parameter R of 'Function' has inconsistent values: Unit, T

我理解它发生的原因:所有 lambda 都是 FunctionN 接口(interface),所有 FunctionN 接口(interface)都扩展了一些名为 Function 的标记接口(interface),它可以' t 被调用。但最后一个也是上面提到的泛型冲突和错误的根本原因。

我的问题可能要问 Kotlin 团队:所有 FunctionN 都扩展 Function 接口(interface)有什么原因吗?也许一些内部/字节码的东西对我们来说并不明显,但在底层进行了一些棘手的性能优化。

最佳答案

https://github.com/JetBrains/kotlin/blob/master/spec-docs/function-types.md给出了一些关于 Function 的使用的有限信息:

  • Introduce a physical class Function and unlimited number of fictitious (synthetic) classes Function0, Function1, ... in the compiler front-end

  • Provide a way to get arity of an arbitrary Function object (pretty straightforward).

  • Hack is/as Function5 on any numbered function in codegen (and probably KClass.cast() in reflection) to check against Function and its arity.

(注意:虚构的 Function* 类在 kotlin 包中,kotlin.jvm.functions.Function* 接口(interface)是真实的。)

目标部分列出了此方法修复的问题:

  • Get rid of 23 hardwired physical function classes. One of the problems with them is that they should be effectively duplicated in reflection which means a lot of physical classes in kotlin-runtime.jar.
  • Make extension functions assignable to normal functions (and vice versa), so that it's possible to do listOfStrings.map(String::length)
  • Allow functions with more than 23 parameters, theoretically any number of parameters (in practice 255 on JVM).
  • At the same time, allow implementing Kotlin functions easily from Java: new Function2() { ... } and overriding invoke only would be the best. Enabling SAM conversions on Java 8 would also be terrific.

关于kotlin - 在 Kotlin 中扩展具有不同签名的 2 个 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56292196/

相关文章:

Kotlin 在类级别具体化类型

kotlin - 如果kotlin包具有多个主要功能,该如何调用特定功能?

kotlin - Page 类的 graphql 架构定义应该是什么样子?

android - 如何使用刷新 token 在AWS Amplify Android中获取新的ID token ?

android - ImageView 不会出现在 Activity 上(在 AppCompatActivity 上没问题)

generics - kotlin 中的递归类型参数

kotlin - 避免在子协程异常时取消父作业

java - Android Paho Mqtt - close() 与 close() 对比unregisterResources() - 内存不足错误

android - AWS S3文件上传与retrofit2视频/图像损坏

class - Kotlin 中的调用构造函数引用