如何转换可比较的<a> into Ordering[A] in Scala

时间:2016-01-14 12:34:33

标签: scala

Even if it's really straightforward, e.g. for LocalDate :

  implicit val ord : Ordering[java.time.LocalDate] = new Ordering[java.time.LocalDate] {
    override def compare(x: LocalDate, y: LocalDate): Int = x.compareTo(y)
  }

Is there a way to convert a Comparable<A> into Ordering[A].

I've tried to import import scala.math.Ordering._ but I get this error

diverging implicit expansion for type Ordering[java.time.LocalDate]
[error] starting with method comparatorToOrdering in trait LowPriorityOrderingImplicits

1 个答案:

答案 0 :(得分:2)

通常,您应该能够从实现Comparable的类型中获取隐式排序。遗憾的是,Java没有类型差异,LocalDate实现了Comparable[ChronoLocalDate]而不是Comparable[LocalDate],所以这不起作用:

implicitly[Ordering[java.time.chrono.ChronoLocalDate]] // ok
implicitly[Ordering[java.time.LocalDate]] // no implicit found

但是,您可以使用其他构造函数,例如

Ordering.by[java.time.LocalDate, java.time.chrono.ChronoLocalDate](identity)

Ordering.fromLessThan[java.time.LocalDate] { (a, b) => a.compareTo(b) < 0 }