实现具有Scala的递归类型和边界的Java接口

时间:2014-11-26 16:34:03

标签: java scala generics types

我遇到了一个问题,可以通过以下Java类进行总结:

public class Foo<T extends Foo> {}

public class Bar<T extends Foo> {}

public interface AnInterface {
    public <T extends Foo, S extends Bar<T>> void doSomething(T thing, S other);
}

我正在尝试从Scala代码实现AnInterface,这是我的IDE建议:

class AnImplementation extends AnInterface {
  override def doSomething[T <: Foo[_], S <: Bar[T]](thing: T, other: S): Unit = ???
}

这不会编译,因为编译器会产生以下错误:

type arguments [T] do not conform to class Bar's type parameter bounds [T <: foo.Foo[_ <: foo.Foo[_ <: foo.Foo[_ <: AnyRef]]]]

我试图用几种方法解决这个问题;一些失败的实验是:

// Failing with: method doSomething has incompatible type
override def doSomething[T <: Foo[_ <: Foo[_]], S <: Bar[T]](thing: T, other: S): Unit = ???

// Failing with: illegal cyclic reference involving type T
override def doSomething[T <: Foo[_ <: T], S <: Bar[T]](thing: T, other: S): Unit = ???

// Failing with: illegal cyclic reference involving type T
override def doSomething[T <: Foo[V] forSome { type V <: T }, S <: Bar[T]](thing: T, other: S): Unit = ???

// Failing with: method doSomething has incompatible type
override def doSomething[T <: Foo[V] forSome { type V <: Foo[_] }, S <: Bar[T]](thing: T, other: S): Unit = ???

有没有人知道如何解决这个问题?是不是可以从Scala实现这样的Java接口?

1 个答案:

答案 0 :(得分:0)

您似乎没有正确地参数化类。我相信这就是你所追求的:

public class Foo<T extends Foo<T>> {}

public class Bar<T extends Foo<T>> {}

public interface AnInterface {
  <T extends Foo<T>, S extends Bar<T>> void doSomething(T thing, S other);
}

然后实施变为:

class AnImplementation extends AnInterface {
  override def doSomething[T <: Foo[T], S <: Bar[T]](thing:T, other:S):Unit = ???
}