Reputation: 11
As part of a trivial exercise, I am trying to implement the following Java interface:
public interface Sort {
@SuppressWarnings("rawtypes")
public ArrayList<Comparable> sort(ArrayList<Comparable> table);
}
With a Java class it is extremely easy to achieve. However, Scala's type inference seems to be problematic when dealing with Collections.sort()
. Here is my Scala implementation:
class SortImpl extends Sort {
override def sort(table: util.ArrayList[Comparable[_]]): util.ArrayList[Comparable[_]] = {
util.Collections.sort(table)
table
}
}
And here's the error I get when running some tests (that mainly test the method with ArrayList<Double>
, ArrayList<Integer>
, etc.)
Error:(20, 22) inferred type arguments [Comparable[_]] do not conform to method sort's type parameter bounds [T <: Comparable[_ >: T]]
util.Collections.sort(table)
^
Error:(20, 27) type mismatch;
found : java.util.ArrayList[Comparable[_]]
required: java.util.List[T]
Note: Comparable[_] >: T, but Java-defined trait List is invariant in type E.
You may wish to investigate a wildcard type such as `_ >: T`. (SLS 3.2.10)
util.Collections.sort(table)
^
I have found examples dealing with this issue, for a specific class only, such as: Sort unbound Comparable in Scala
Moreover, I can't modify the interface. Is there a way to implement this in Scala?
Upvotes: 0
Views: 123
Reputation: 12783
Try that:
scala> import java.{util => u}
import java.{util=>u}
scala> def sort[T <: Comparable[T]](t: u.ArrayList[T]):u.ArrayList[T] = {
u.Collections.sort(t); t
}
sort: [T <: Comparable[T]](t: java.util.ArrayList[T])java.util.ArrayList[T]
Upvotes: 1