[英]Implementing a Java interface featuring recursive type and bounds from Scala
我有一个问题可以通过以下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接口?
看起来你没有正确地参数化类。 我相信这就是你所追求的:
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 = ???
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.