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
答案 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 }