这是显示此问题的最小演示代码:
interface A
fun <T1, T2> test() where T2 : T1, T2 : A {}
当我尝试编译它时,编译器会报错:
Error:(81, 25) Kotlin: Type parameter cannot have any other bounds if it's bounded by another type parameter
我阅读了 Kotlin Language Specification ,但只找到了以下绑定(bind)限制:
A type-parameter cannot specify itself as its own bound, and several type-parameters cannot specify each other as a bound in a cyclic manner.
它没有解释我遇到的限制。
我探索了 Kotlin 的问题跟踪器,发现了一个关于此限制的问题:Allow to inherit a type parameter from another type parameter and a class : KT-13768。但是,此问题已被以下原因拒绝(2017 年 5 月 6 日更新:此问题已由 Stanislav Erokhin 重新打开):
I don't think we can compile the code correctly to JVM if we remove this restriction.
By Andrey Breslav
那么问题来了:如果我们去掉这个限制,为什么我们不能正确地将代码编译到 JVM 中呢?
同样的演示也适用于 Scala:
trait A
def test[T1, T2 <: T1 with A](): Unit = {}
这表明Scala可以将代码正确编译到JVM。为什么 Kotlin 不能?在 Kotlin 中保证可确定的子类型是否是一种限制(我猜。子类型对于 Scala 是不可确定的(Scala 具有图灵完备的类型系统)。Kotlin 可能需要像 C# 这样的可确定子类型。)?
@erokhins (https://stackoverflow.com/a/43807444/7964561) 回答后更新:
在支持 Java 禁止但 JVM 允许的东西时存在一些微妙的问题,尤其是在 Java 互操作性方面。在深入研究 scalac 生成的字节码时,我发现了一个有趣的问题。我在演示中修改 Scala 代码如下:
trait A
trait B
def test[T1 <: B, T2 <: T1 with A](t1: T1, t2: T2): Unit = {}
class AB extends A with B
Scalac 将生成以下签名:
// signature <T1::LB;T2:TT1;:LA;>(TT1;TT2;)V
// descriptor: (LB;LB;)V
public <T1 extends B, T2 extends T1 & A> void test(T1, T2);
在 Scala 中使用 test(new AB, new AB)
调用 test
将成功,因为 Scalas 调用签名 (LB;LB;)V
;但是在 Java 中使用 test(new AB(), new AB());
调用会失败,因为 Java 调用签名 (LB;Ljava/lang/Object;)V
,在运行时导致 java.lang.NoSuchMethodError
。这意味着scalac在放松这个限制后生成了一些不能在Java中调用的东西。 Kotlin 放松后可能会遇到同样的问题。
最佳答案
这个限制是因为java(语言)有它:
interface A {}
// Error:(7, 26) java: a type variable may not be followed by other bounds
<T1, T2 extends T1 & A> void test() {}
我们假设这在字节码级别也是禁止的。 我深入研究它,似乎它是允许的,并且 scalac 生成以下签名:
// access flags 0x1
// signature <T1:Ljava/lang/Object;T2:TT1;:LA;>()V
// declaration: void test<T1, T2T1 extends A>()
public test()V
所以,我们可能会在未来的 kotlin 版本中支持这种情况。
附:据我所知,Kotlin 具有可判定的子类型,并且可判定性不受此影响。
关于types - 如果 Kotlin 中的类型参数受另一个类型参数的限制,为什么它不能有任何其他范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43790137/