I came across this question because I also wanted to compare joda DateTime objects using relational operators.
Daniel answered me in the right direction: the implications present in scala.math.Ordered convert an instance of A extends java.lang.Comparable[A] to Ordered[A] - they just need to be put into scope. The easiest way to do this (which I learned here , btw) is via the implicitly method:
val aOrdering = implicitly[Ordering[A]] import aOrdering._
The conclusion is that org.joda.time.DateTime does not extend or implement Comparable itself; it inherits (indirectly) from org.joda.time.ReadableInstant , which extends Comparable . So:
val dateTimeOrdering = implicitly[Ordering[DateTime]] import dateTimeOrdering._
will not compile because DateTime does not extend Comparable[DateTime] . To use the Ordered relational operators on DateTime , you should do this instead:
val instantOrdering = implicitly[Ordering[ReadableInstant]] import instantOrdering._
which works because ReadableInstant extends Comparable[ReadableInstant] , and implicit conversions in Ordered can convert it to Ordered[ReadableInstant] .
So far so good. However, there are situations when Ordered[ReadableInstant] not good enough. (I came across ScalaTest bigger and smaller than Matchers .) To get Ordered[DateTime] , I was forced to do this:
implicit object DateTimeOrdering extends Ordering[DateTime] { def compare(d1: DateTime, d2: DateTime) = d1.compareTo(d2) }
There seems to be an easier way, but I could not figure it out.
Mark tye
source share