1

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

2 回答 2

4

语言规范

类型T隐式范围由与隐式参数类型相关联的类的所有伴随模块(第 5.4 节)组成。

页面的以下四分之一定义了关联的含义,但对您的问题而言唯一重要的部分Ordering是关联的Ordering[Int],因此编译器会在伴随对象中查找Ordering,果然,有Int

于 2013-10-24T00:13:29.483 回答
0

我想这是因为 Int 隐含地丰富了 Ordered 特征:

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

于 2013-10-24T00:13:23.453 回答