4

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 ...

Havoc P
  • 8,365
  • 1
  • 31
  • 46
  • Please refer to [How to define an Ordering in Scala?](http://stackoverflow.com/questions/9061141/how-to-define-an-ordering-in-scala) – pedram bashiri Nov 11 '16 at 19:16

5 Answers5

5

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.)

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
4

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)
  }
}
Nick Evans
  • 53
  • 5
1

Best possibility, but with additional dependency: NScala-Time wrapper for Joda DateTime has DateTimeOrdering implicit:

https://github.com/nscala-time/nscala-time/blob/master/src/main/scala/com/github/nscala_time/time/Implicits.scala

1
times.max(Ordering.fromLessThan[DateTime](
  DateTimeComparator.getInstance.compare(_,_) < 0))

which is ugly too!

Where does your asScala come from?

additional thoughts

I'm not sure there is a better way. DateComparator implements Comparator.

the max method expects an Ordering[DateTime]. Ordered and Ordering are invariant in Scala. So I think the case is necessary to use asScala.

huynhjl
  • 41,520
  • 14
  • 105
  • 158
0

In case you are willing to use Saddle, there's an implicit Datetime ordering defined there, in which case this is enough to solve the issue:

import org.saddle.time._
Svend
  • 6,352
  • 1
  • 25
  • 38