Java F-Bound 接口绑定

Java F-Bound bound by interface

表示法:Inter为接口; Abs[N] 是一个摘要 class.

以下代码在 Java 中运行良好,没有问题:

public class Impl<T extends Abs1<T>> extends Abs2<T> {...}

但是,如果你想在 T 上引入另一个接口绑定,我还没有找到任何简单的方法来做到这一点,即:

public class Impl<T extends Inter & Abs1<T>> extends Abs2<T> {...}

将不起作用,因为 Abs1 作为抽象 class 不能用作边界参数。我找到的最简单但丑陋(丑陋吗?)的解决方案是:

public class Impl<B extends Inter, T extends Abs1<B>> extends Abs2<T> {...}

我有一种预感,在具有这些特征的 Scala 中存在更优雅的解决方案,但是 Java 有什么提示吗?

我的天……好吧,这很尴尬。我太专注于 F-Bound,以至于我忘记了这直接来自 JLS, section 4.4:

Every type variable declared as a type parameter has a bound. If no bound is declared for a type variable, Object is assumed. If a bound is declared, it consists of either:

  • a single type variable T, or

  • a class or interface type T possibly followed by interface types I1 & ... & In.

换句话说,(抽象的)class声明必须在交集类型中首先出现。所描述的行为与 F-Boundedness 无关。即,以下作品:

public class Impl<T extends Abs1<T> & Inter> extends Abs2<T> {...}

这在Java Tutorial中也有描述。如果考虑一下,它是 self-explanatory,因此解析器有一种简单的方法来检查 double-inheritance(这是被禁止的)。