Re-using Java generic collections in Scala without trait Object

Go To StackoverFlow.com

1

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!

2012-04-03 19:35
by Nikolaos
This looks a lot like a type erasure thing caused by using generic arrays in the first place - Louis Wasserman 2012-04-03 19:39
I think you meant x.test(array), right - leedm777 2012-04-03 20:25
@dave: yes, edite - Nikolaos 2012-04-03 20:27


7

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

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

2012-04-03 20:23
by Didier Dupont