I'm using some java.util.Date (which implements java.lang.Comparable) and would like to be able to use it nicely, e.g. use < and >= instead of "compareTo(other) == 1". Is there a nice way to just easily mix in something like scala.math.Ordered without a lot of boiler plate?
-
you could do an implicit from date to ordered, are you looking for something else ? – aishwarya Dec 13 '11 at 04:35
3 Answers
In the Ordering companion object there is an implicit conversion from Comparable[A] to Ordering[A]. So you can do this:
import java.util.Date
val dateOrdering = implicitly[Ordering[Date]]
import dateOrdering._
val now = new Date
val then = new Date(now.getTime + 1000L)
println(now < then) // true

- 1,205
- 9
- 13
-
4A slight caveat: If you have a class `B` that inherits from `A implements Comparable` (Java syntax), you can't get `implicitly[Ordering[B]]`. You have to use `implicitly[Ordering[A]]` instead. – Tim Yates Jun 14 '13 at 17:22
-
Very nice. Hopefully Scala 2.12 makes this work by default / easier - also for `Instant` etc. – akauppi Oct 09 '16 at 13:26
I know this is an old question, but here's a slightly simpler solution that may not have been available when the question was asked.
import scala.math.Ordering.Implicits._
Any Java types that implement Comparable
should then work seamlessly with comparison operators. For example,
import java.time.Instant
val x = Instant.now()
val y = x.plusSeconds(1)
print(x < y) // prints true
print(x <= y) // prints true
print(x > y) // prints false

- 141
- 1
- 3
-
Nice answer but sadly this only works for infix operators. `x max y` works but looks pretty strange. – steinybot Jun 26 '20 at 02:52
You can't mix in Ordered
in this case, afaik... I tried it and ran into difficulties because compareTo
is defined both there and in java.lang.Comparable
. The compiler complains that Ordered
doesn't use override
in its definition of the method; I don't know how to get around that.
So define an implicit Ordering[Date]
. You can put this DateOrdering
object anywhere (e.g. in companion object).
import java.util.Date
implicit object DateOrdering extends Ordering[Date] {
def compare(x: Date, y: Date) = x compareTo y
}
Then in your code:
import DateOrdering._
val a = new Date
Thread.sleep(1000)
val b = new Date
println(a < b) // prints true
println(a >= b) // prints false
The Ordering
object contains an implicit def mkOrderingOps (lhs: T): Ops
. The Ops
class contains the <
. >=
etc methods, and this implicit def is an example of the pimp my library pattern on whatever the type parameter of the Ordering is (here, any Date
instance).

- 50,650
- 20
- 113
- 180