Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Temporal not extend Comparable in Java 8 jsr310

The documentation for java.time.temporal.Temporal contains the following note:

Implementation Requirements: [...] All implementations must be Comparable.

Why does Temporal not just extend Comparable?

Background: I want to work with comparable temporals (not with subtypes like LocalDateTime etc.) and have to resort to a somewhat illegible type <T extends Temporal & Comparable<T>> which also messes up NetBeans' auto-complete feature.

Edit: I want to implement a temporal interval. The obvious implementations for contains(Interval i), contains(Temporal t), overlaps(...), adjoins(...) etc. use Comparable::compareTo(Comparable c) to compare the start and end points, but for interoperability (toDuration(), parse(CharSequence cs)) I need e.g. Duration::between(Temporal s, Temporal e) or SubtypeOfTemporal::parse(CharSequence cs) (yielding Temporal).

like image 745
René Avatar asked May 26 '14 13:05

René


People also ask

What does temporal mean in Java?

Java For Testers A temporal field is a field of date-time, such as month-of-year or hour-of-minute. These fields are represented by the TemporalField interface and the ChronoField class implements this interface.

What is an instant in the Java 8 date and time API?

The Java Date Time API was added from Java version 8. instant() method of Clock class returns a current instant of Clock object as Instant Class Object. Instant generates a timestamp to represent machine time. So this method generates a timestamp for clock object.


1 Answers

If it implemented Comparable<Temporal>, every suclass instance would have to be comparable with any other subclass instance. And comparing an Instant with a LocalDate, for example, doesn't make sense.

Given that the contract mandates that they are comparable, you can cast T to Comparable<T> and safely ignore the compiler warning.

like image 157
JB Nizet Avatar answered Oct 11 '22 20:10

JB Nizet