1
votes

In scala, to make a class comparable we extends Ordered[T] on the class

case class A(i: Int) extends Ordered[A] {
  def compare(that: A): Int = this.i compare that.i 
} 

and Iteratable[A]'s method sorted requires implicit parameter of type scala.math.Ordering[A] to sort Iterable[A]

Seq[A](A(2),A(1)).sorted // Seq(A(1),A(2)) Ordering will provide Ordering[A]
Seq[A](A(2),A(1)).sorted(Ordering[A]) // Seq(A(1),A(2))

and the Ordering companion object provides an implicit Ordering[T] for Iterable[A]

My question: How can the Ordering object can provide Ordering[T] to sorted.

Since [T] will be removed by JVM and it is impossible to know difference between

Ordering[A] and Ordering[Int]

How come it can work??

1

1 Answers

4
votes

How come it can work?

Implicits are a compile time feature. That is, when you compile your code, the compiler enforces rules which need to check out. In this particular case, an implicit of type Ordering[Int] needs to be available in scope, otherwise you'll get a compilation error.

This means that at run-time, even though the types are erased, you can guarantee that there will be an Ordering[Int] available, even though it will look like an Ordering(obj: Object), you've already fulfilled the guarantee of it being able to order the underlying Int objects which otherwise wouldn't allow your code to compile.