How to circumvent invariance? E.g. passing Array[T] to func(Array[U]) where T<:U

Viewed 116

I'm practicing scala using an existing java library. It's quite common to pass Array[T] to func(Array[U]) where T<:U. For example:

Java:

public class Quick { ...
    public static void sort(Comparable[] a) { ... }
}

public class Edge implements Comparable<Edge> { ... }

public class EdgeWeightedGraph { ...
    public Iterable<Edge> edges() { ... }
}

Scala:

class Kruskal(private val G: EdgeWeightedGraph) {
    init()
    private def init() = {
        val es = G.edges().asScala.toArray
        /* **Error** Type mismatch, 
         *           expected: Array[Comparable[_]], 
         *           actual: Array[Edge]
         */
        Quick.sort(es)  
        ...
    }
}

I believe it's because the fact that Array is invariant. Here's my attempt to circumvent this, but it looks ugly and inefficient:

val es = G.edges().asScala.map(_.asInstanceOf[Comparable[_]]).toArray)
Quick.sort(es)

How do I do it in a better way?

1 Answers
Related