0

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...

Chris Bedford
  • 2,560
  • 3
  • 28
  • 60
  • Check out [What are Scala context and view bounds?](https://stackoverflow.com/questions/4465948/what-are-scala-context-and-view-bounds). View bounds are deprecated. – Chris Martin Aug 29 '15 at 10:03

1 Answers1

3

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

Chris Bedford
  • 2,560
  • 3
  • 28
  • 60
  • Context bounds are very often used (as in this case) with [_type classes_](http://danielwestheide.com/blog/2013/02/06/the-neophytes-guide-to-scala-part-12-type-classes.html) -- in fact, I'd say, type classes are the reason they have been introduced. – phipsgabler Aug 29 '15 at 14:09