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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With