Yann Moisan
Yann Moisan

Reputation: 8281

Howto convert a Comparable<A> into Ordering[A] in 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

Upvotes: 3

Views: 627

Answers (1)

0__
0__

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

Related Questions