How to convert DateTimeComparator to Ordering [DateTime] in Scala

I just typed this, which seems a little ugly:

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

times is the sequence org.joda.time.DateTime.

There should be a better way to get this Ordering object for a DateTime. There is?

In particular, it would be great to lose asInstanceOf ...

+4
source share
5 answers

Another possibility is to use comparatorToOrdering :

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

I guess that is what the asScala call asScala . This is not prettier, I know: - |

(Unfortunately, casting is required because DateTimeComparator implements Comparator as a raw type.)

+5
source

You can also write your own class that extends the Ordering property, and use it to enter 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) } } 
+4
source

Better feature, but with an 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

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

which is also ugly!

Where is your asScala ?

additional thoughts

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

The max method expects Ordering[DateTime] . Order and order are invariant in Scala. Therefore, I believe that it is necessary to use asScala .

+1
source

If you want to use a saddle, an implicit Datetime ordering is defined there, in which case this is enough to solve the problem:

 import org.saddle.time._ 
0
source

All Articles