从Scala实现具有递归类型和边界的Java接口
我有一个问题可以用以下Java类来概括:从Scala实现具有递归类型和边界的Java接口,java,scala,generics,types,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); } 这不会编译,因为编译器会产生以下错误
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);
}
这不会编译,因为编译器会产生以下错误:
type arguments [T] do not conform to class Bar's type parameter bounds [T <: foo.Foo[_ <: foo.Foo[_ <: foo.Foo[_ <: AnyRef]]]]
类型参数[T]不符合类栏的类型参数界限[T看起来您没有正确地参数化类。我相信这就是您所追求的:
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);
}
公共类Foo{}
公共类Bar{}
公共接口{
使某物无效(T物,S物);
}
然后实现成为:
class AnImplementation extends AnInterface {
override def doSomething[T <: Foo[T], S <: Bar[T]](thing:T, other:S):Unit = ???
}
类AnImplementation扩展了接口{
override def doSomething[T我猜这是应该做的事情,事实上你说'Bar'中的类型是泛型类型T,你知道扩展类中的类型T,所以你可以硬编码它?(我很久没有在scala中编码了,所以可能误读了!))感谢您的评论,问题在于类型T不是在类级别(即在AnImplementation
上)定义的,而是仅在方法级别(即在doSomething
上)定义的。问题与条码的上下文绑定有关,我需要的是一种方法来满足这一点,而不会以一种不算是接口实现的方式改变函数。我没有时间对其进行测试,但您是否尝试过一些t{键入T@Imm谢谢你的想法,但如果我只是将其替换为T@AldoStracquadaniooverride def doSomething[T
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 = ???
}