I was looking at the source for Sorting.scala, and was curious about the definition of the last method in the source snippet below.
object Sorting {
/** Quickly sort an array of Doubles. */
def quickSort(a: Array[Double]) { sort1(a, 0, a.length) }
/** Quickly sort an array of items with an implicit Ordering. */
def quickSort[K: Ordering](a: Array[K]) { sort1(a, 0, a.length) } //<<??
The type parameter 'K' seems to be constrained to be a subtype (perhaps?) of 'Ordering'... But I have never seen this syntax.
I would sort of (no pun intended) understand if the method were defined something like:
def quickSort[K <% Ordering[K]](a: Array[K]) { sort1(a, 0, a.length) }
But I am puzzled by the meaning of a constraint that has just the colon. Any links to relevant documentation or further (explained) examples would be awesome.
Thanks in advance...
Turns out this is a 'Context Bound'. Found the answer in a very good book I'm now reading 'Programming Scala'. From Chap 5. on Implicit arguments... here is an example that explains what is going on:
case class MyList[A](list: List[A]) {
def sortBy1[B](f: A => B)(implicit ord: Ordering[B]): List[A] =
list.sortBy(f)(ord)
def sortBy2[B : Ordering](f: A => B): List[A] =
list.sortBy(f)(implicitly[Ordering[B]])
}
val list = MyList(List(1,3,5,2,4))
list sortBy1 (i => -i)
list sortBy2 (i => -i)
The type parameter B : Ordering is called a context bound. It implies the second, implicit argument list that takes an Ordering[B] instance.
More here