gpt4 book ai didi

java - 从 Scala 实现具有递归类型和边界的 Java 接口(interface)

转载 作者:搜寻专家 更新时间:2023-11-01 03:51:20 24 4
gpt4 key购买 nike

我有一个问题可以用以下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 接口(interface)是不可能的吗?

最佳答案

看起来您没有正确地参数化类。我相信这就是您所追求的:

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 = ???
}

关于java - 从 Scala 实现具有递归类型和边界的 Java 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27154322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com