Why LocalDate doesn't implements Comparable<LocalDate>?
Asked Answered
Q

2

5

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

Quaff answered 30/11, 2018 at 11:27 Comment(3)
It implements Comparable<ChronoLocalDate> as well as ChronoLocalDate and by implementing those two, every instance of it is of course comparable to another LocalDate instance.Agosto
Link: Online demonstration that you can sort by the natural order of LocalDateZincography
#38059691Himyarite
A
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.

Agosto answered 30/11, 2018 at 11:44 Comment(0)
H
4

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.

Himyarite answered 30/11, 2018 at 14:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.