3

Initial Problem:

In Scala, I would like to use implicit Ordering[T]#Ops to compare two LocalDate.

It just to use "operators" like > instead of isAfter.

It should be just an import: import scala.math.Ordering.Implicits._

Inspection:

Looks like it works with LocalTime and doesn't with LocalDate because LocalTime instead of LocalDate implements Comparable<LocalTime>.

Question:

I wondering,

Why LocalDate implements Comparable<ChronoLocalDate> instead of Comparable<LocalDate>?

mkUltra
  • 2,382
  • 18
  • 38
  • 4
    It implements `Comparable` as well as `ChronoLocalDate` and by implementing those two, every instance of it is of course comparable to another `LocalDate` instance. – deHaar Nov 30 '18 at 11:29
  • 2
    [Link: Online demonstration that you can sort by the natural order of `LocalDate`](https://ideone.com/BTawTI) – Ole V.V. Nov 30 '18 at 12:41
  • 2
    https://stackoverflow.com/questions/38059191/how-make-implicit-ordered-on-java-time-localdate/ – Alexey Romanov Nov 30 '18 at 19:31

2 Answers2

9

LocalDate in fact implements Comparable<ChronoLocalDate> as well as ChronoLocalDate and by implementing those two, every instance of it is of course comparable to another LocalDate instance.

You can have a look at the JavaDocs for LocalDate on Oracle's website.

ChronoLocalDate is an interface that is implemented by different types of calendars in order to make them all comparable to each other. That is because there are JapaneseDate, ThaiBuddhistDate, HijrahDate and at least one more. Totally different calendars that are all comparable to each other, which is great. LocalTime, on the other hand, is just a time representation with different time zones and just doesn't have to go this interface-way to be comparable to time representations of different locales.

deHaar
  • 11,298
  • 10
  • 32
  • 38
3

To make operators work, you just need another line in addition to the import, defining the desired Ordering (assuming Scala 2.12):

implicit val localDateOrdering: Ordering[LocalDate] = _.compareTo(_)

If you want to use it in many classes, define it in an object and import where necessary.

Alexey Romanov
  • 154,018
  • 31
  • 276
  • 433