【问题标题】:Is there a Implicit value conflicts in Ordering[A] in scala's source code?scala 源代码中的 Ordering[A] 中是否存在隐式值冲突?
【发布时间】:2017-02-21 01:56:12
【问题描述】:
trait LowPriorityOrderingImplicits {

/** This would conflict with all the nice implicit Orderings
    *  available, but thanks to the magic of prioritized implicits
    *  via subclassing we can make `Ordered[A] => Ordering[A]` only
    *  turn up if nothing else works.  Since `Ordered[A]` extends
    *  `Comparable[A]` anyway, we can throw in some Java interop too.
    */

implicit def ordered[A <% Comparable[A]]: Ordering[A] = new Ordering[A] {
def compare(x: A, y: A): Int = x compareTo y
 }

  implicit def comparatorToOrdering[A](implicit cmp: Comparator[A]): Ordering[A] = new Ordering[A] {
    def compare(x: A, y: A) = cmp.compare(x, y)
  }

}

那里,两个隐式函数(ordering[A] 和comparatorToOrdering[A])都返回Ordering[A],它应该冲突,但是为什么它在那里工作呢?

【问题讨论】:

标签: scala


【解决方案1】:

仅对于某些类型 A 存在隐式转换 A =&gt; Comparable[A] 和隐式 Comparator[A]。这些隐式导致模棱两可的唯一方法是它们自己的隐式参数都解析。在这种情况下,它会失败:

class Foo

implicit val fooComp = new java.util.Comparator[Foo] { def compare(a: Foo, b: Foo): Int = 0 }

val fooComparable = new java.lang.Comparable[Foo] { def compareTo(foo: Foo): Int = 0 }

implicit def foo2Comp(foo: Foo): Comparable[Foo] = fooComparable

scala> implicitly[Ordering[Foo]]
<console>:16: error: ambiguous implicit values:
 both method ordered in trait LowPriorityOrderingImplicits of type [A](implicit evidence$1: A => Comparable[A])scala.math.Ordering[A]
 and method comparatorToOrdering in trait LowPriorityOrderingImplicits of type [A](implicit cmp: java.util.Comparator[A])scala.math.Ordering[A]
 match expected type Ordering[Foo]
       implicitly[Ordering[Foo]]
                 ^

因此,从技术上讲,可能会出现模棱两可的隐含错误,但应该非常罕见。如果某个东西已经是Comparable,则不需要隐含的Comparator。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 2011-06-05
    • 1970-01-01
    • 2019-03-11
    • 2016-07-25
    • 1970-01-01
    相关资源
    最近更新 更多