【问题标题】:Re-using Java generic collections in Scala without trait Object在没有 trait Object 的情况下在 Scala 中重用 Java 泛型集合
【发布时间】:2012-04-03 19:35:51
【问题描述】:

我正在尝试重用我编写的 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 代码,而不是移植整个东西......)

也许某种隐含的定义可以起到拯救作用? 谢谢!

【问题讨论】:

  • 这看起来很像首先使用泛型数组引起的类型擦除?
  • 我想你的意思是x.test(array),对吧?

标签: java scala generics collections traits


【解决方案1】:

限制def test[T &lt;: AnyRef] 可以解决问题。

没错,通用 java 方法不应该接受,例如,int[] (Array[Int]) 参数。 Blah[Int] 将被视为Blah&lt;Integer&gt;Array[Int]int[],而不是Integer[]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多