I planned to write a class that extends java.time.YearMonth
with the purpose to extend the YearMonth
with a method that enables me to stream the LocalDate
s of that YearMonth
:
public class ExtendedYearMonth extends YearMonth {
public Stream<LocalDate> days() {
LocalDate firstOfMonth = this.atDay(1);
LocalDate lastOfMonth = firstOfMonth.with(TemporalAdjusters.lastDayOfMonth());
return firstOfMonth.datesUntil(lastOfMonth);
}
}
Well, that plan instantly failed when I found YearMonth
to be a final class
⇒ final class
es are not extensible.
I could of course write a class like this one
public class ExtendedYearMonth {
private YearMonth yearMonth;
// parameterized constructor, getters and setters omitted for brevity
public Stream<LocalDate> days() {
LocalDate firstOfMonth = this.yearMonth.atDay(1);
LocalDate lastOfMonth = firstOfMonth.with(TemporalAdjusters.lastDayOfMonth());
return firstOfMonth.datesUntil(lastOfMonth);
}
}
but that's not what I wanted because it requires me to instantiate a YearMonth
and an ExtendedYearMonth
just to stream
(and filter
, the main purpose) the LocalDate
s of a specific month in a specific year.
The JavaDocs of YearMonth
just state that it's final
, but not why it is final
:
public final class YearMonth
...
YearMonth is an immutable date-time object that represents the combination of a year and month.
...
Why was YearMonth
made final
?
Or more accurate : What's the benefit of final class YearMonth
over a class YearMonth
?
I cannot imagine any reason...
I know, to answer this one is required to have insight to the design decisions that may be public somewhere in the www, but, unfortunatley, I don't have this insight and I haven't found a source so far.
In Kotlin, this doesn't matter because one can write an extension function without having to inherit from that class
. That's a nice feature of Kotlin, but Java doesn't have this (for now) and I refuse to write a wrapper class for this.
I could also ask why such a method isn't available in YearMonth
or wasn't added when LocalDate
got datesUntil
in Java 9, but that would be a second question in a single post, which is generally frowned (and down- or close-voted) upon, so I may ask that later in a different post.
My current solution is a public static Stream<LocalDate> daysOf(YearMonth yearMonth)
which does what the above code does, but I have to pass an instance to a static
method instead of directly using a method of it. That's working for my requirement, but it's still not what I consider a near-to-perfection solution.