简体   繁体   中英

Re-using Java generic collections in Scala without trait Object

I'm trying to re-use a Java generic collection I wrote, looks a lot like this:

public class Blah<T>
   implements List<T>
{
...
   public void test(T[] array) {
   ...
   }
...
}

When consumed from a Scala generic collection that uses the above, I'm getting a compilation error, where I notice that the Blah class method expects not T, but T with java.lang.Object!

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
}

Is there a way to avoid this situation without re-writing the Blah class in Scala? (That works, but I have too much such Java code and rather not port the whole thing...)

Maybe perhaps some kind of implicit definition could come to the rescue? Thanks!

Restricting def test[T <: AnyRef] does the trick.

Rightly so, the generic java method should not accept, eg, an int[] ( Array[Int] ) parameter. Blah[Int] will be taken as Blah<Integer> , Array[Int] is int[] , which is not Integer[] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM