我正在尝试重新使用我编写的 Java 泛型集合,看起来很像这样:
public class Blah<T>
implements List<T>
{
...
public void test(T[] array) {
...
}
...
}
当从使用上述内容的 Scala 泛型集合中使用时,出现编译错误,我注意到 Blah 类方法不需要 T,而是带有 java.lang.Object 的 T!
Object MyStaticObject {
def test[T](array: Array[T]) = {
val x = new Blah[T]();
x.test(array) // <- error here: Overloaded method with alternatives test[T with java.lang.Object] ... cannot be applied
}
有没有一种方法可以避免这种情况而无需在 Scala 中重写 Blah 类? (这行得通,但我有太多这样的 Java 代码,而不是移植整个代码...)
也许某种隐含的定义可以拯救? 谢谢!
最佳答案
限制 def test[T <: AnyRef]
做的伎俩。
没错,通用 java 方法不应该接受,例如 int[]
。 ( Array[Int]
) 参数。
Blah[Int]
将被视为 Blah<Integer>
, Array[Int]
是int[]
, 这不是 Integer[]
.
关于java - 在没有特征对象的 Scala 中重用 Java 泛型集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10000126/