scala parameterized type with constraint appearing after the colon?

纵然是瞬间 提交于 2019-12-12 03:38:42

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/32283727/scala-parameterized-type-with-constraint-appearing-after-the-colon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!