Reputation: 8281
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
Upvotes: 3
Views: 627
Reputation: 67290
Normally you should be able to get an implicit ordering from a type that implements Comparable
. Unfortunately Java does not have type variance, though, and LocalDate
implements Comparable[ChronoLocalDate]
instead of Comparable[LocalDate]
, so that doesn't work:
implicitly[Ordering[java.time.chrono.ChronoLocalDate]] // ok
implicitly[Ordering[java.time.LocalDate]] // no implicit found
However, you can use other constructors, for example
Ordering.by[java.time.LocalDate, java.time.chrono.ChronoLocalDate](identity)
or
Ordering.fromLessThan[java.time.LocalDate] { (a, b) => a.compareTo(b) < 0 }
Upvotes: 5