简体   繁体   中英

Context Bound confusion

When I declare class Pair[T : Ordering] , it requires that there is an implicit value of Ordering[T] . In the example below, I am trying to figure out where the implicit value of Ordering[Int] is coming from.

It looks like scala.math.Ordering.Int should be the implicit value here, but it has not been imported, so where is the implicit value being gotten from?

class Pair[T : Ordering](val first: T, val second: T) {
    def smaller(implicit ord: Ordering[T]) = 
        if(ord.compare(first, second) < 0) first else second
}

object Run extends App {
    val p = new Pair[Int](2, 3)
}   

From the language specification :

The implicit scope of a type T consists of all companion modules (§5.4) of classes that are associated with the implicit parameter's type.

The following quarter of a page defines what associated with means here, but the only part that matters for your question is that Ordering is associated with Ordering[Int] , so the compiler goes looking in the companion object for Ordering , and sure enough, there's Int .

I guess it's because Int is implicitly enriched with Ordered trait:

http://docs.scala-lang.org/sips/pending/implicit-classes.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM