Stuart Harrell
Stuart Harrell

Reputation: 127

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)
}   

Upvotes: 1

Views: 96

Answers (2)

Travis Brown
Travis Brown

Reputation: 139038

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.

Upvotes: 4

Ashalynd
Ashalynd

Reputation: 12563

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

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

Upvotes: 0

Related Questions