Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic use of a Java comparable object

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?

like image 795
Heptic Avatar asked Dec 13 '11 01:12

Heptic


2 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
like image 132
Garrett Rowe Avatar answered Oct 13 '22 16:10

Garrett Rowe


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
like image 34
Lance Arlaus Avatar answered Oct 13 '22 14:10

Lance Arlaus