简体   繁体   English

语境困惑

[英]Context Bound confusion

When I declare class Pair[T : Ordering] , it requires that there is an implicit value of Ordering[T] . 当我声明class Pair[T : Ordering] ,它要求存在Ordering[T]的隐式值。 In the example below, I am trying to figure out where the implicit value of Ordering[Int] is coming from. 在下面的示例中,我试图找出Ordering[Int]的隐含值来自何处。

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? 它看起来像scala.math.Ordering.Int这里应该是隐含值,但是它还没有被导入,所以从哪里得到隐含值?

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. 类型T隐式作用域包含与隐式参数类型相关联的所有类的伴随模块(第5.4节)。

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 . 下一季度的页面定义了此处相关的内容 ,但唯一对您的问题重要的部分是OrderingOrdering[Int]相关联,因此编译器会查找Ordering 的伴随对象 ,当然,还有Int

I guess it's because Int is implicitly enriched with Ordered trait: 我想这是因为Int隐含地使用Ordered trait来丰富:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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