在 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) classesFunction0
,Function1
, ... in the compiler front-endProvide a way to get arity of an arbitrary
Function
object (pretty straightforward).Hack
is/as Function5
on any numbered function in codegen (and probablyKClass.cast()
in reflection) to check againstFunction
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 overridinginvoke
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/