Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert DateTimeComparator to an Ordering[DateTime] in Scala

Tags:

scala

jodatime

I just typed this which seems a little ugly:

val maxTime = times.max(DateTimeComparator.getInstance().asInstanceOf[Comparator[DateTime]] asScala)

times is a sequence of org.joda.time.DateTime.

There must be a better way to get that Ordering object for DateTime. Is there?

In particular it'd be great to lose the asInstanceOf ...

like image 373
Havoc P Avatar asked Dec 22 '22 15:12

Havoc P


2 Answers

Another possibility is to use comparatorToOrdering:

Ordering.comparatorToOrdering(DateTimeComparator.getInstance.asInstanceOf[Comparator[DateTime]])

I suppose that's what the asScala call does. It's not prettier, I know :-|

(The cast is unfortunately required because DateTimeComparator implements Comparator as a raw type.)

like image 110
Jean-Philippe Pellet Avatar answered Feb 09 '23 01:02

Jean-Philippe Pellet


You can also write your own class that extends the Ordering trait, and use this as input to the maximum function:

class JodaDateTimeOrdering extends Ordering[org.joda.time.DateTime] {
  val dtComparer = DateTimeComparator.getInstance()

  def compare(x: DateTime, y: DateTime): Int = {
    dtComparer.compare(x, y)
  }
}
like image 42
Nick Evans Avatar answered Feb 09 '23 01:02

Nick Evans