Scala (case classes) and C# (structs) have support for data classes. When is Java expected to offer support for this language feature?
Scala (case classes) and C# (structs) have support for data classes. When is Java expected to offer support for this language feature?
With a bit of reseach, I ended up with Data Classes and Sealed Types for Java by Brian Goetz.
Here is the JEP, Records (Preview), linking to the above.
Summary - It is just an idea/JEP. So, we cannot tell when it would be implemented (or if it would be implemented at all)
The tentative date is March 2020 for the release of JDK 14.
In Nov. 2019, the JEP 359 about Records (data carriers classes) has been confirmed as being part of Java 14 as a preview (meaning, as commented below by Basil Bourque, it needs to be enabled explicitly and it can be removed in the future).
Still: you can start experimenting with it starting with Java 14, March 2020.
As presented here, record Range(int lo, int hi) would replace
package javax0.geci.tests.record;
import javax0.geci.annotations.Geci;
@Geci("record")
public final class Range {
final int lo;
final int hi;
//<editor-fold id="record">
public Range(final int lo, final int hi) {
this.lo = lo;
this.hi = hi;
}
public int getLo() {
return lo;
}
public int getHi() {
return hi;
}
@Override
public int hashCode() {
return java.util.Objects.hash(lo, hi);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Range that = (Range) o;
return java.util.Objects.equals(that.lo, lo) && java.util.Objects.equals(that.hi, hi);
}
//</editor-fold>
}
Is there an expected date for when Java data classes will be introduced?
Yes: mid-March 2021 given the 6-month cadence of the Java release train.
The Records feature being previewed provide for “declaring classes which are transparent holders for shallowly immutable data”. In other words, a nominal tuple, a specific ordered sequence of elements.
Records are a special kind of class. In defining a record class, you trade away some flexibility for concision. Here is a complete example record class definition:
record Task( String title , String notes , LocalDate due ) {}
Or:
record Dog( Breed breed , Color color , String name ) {}
The compiler implicitly takes care of providing a constructor, member fields, accessor methods, toString, hashCode, and equals. You can optionally override these if desired, such as defining a constructor than validates the inputs.
For more info:
Just make all attributes public and do not add any methods. Usually, it is not recommendable, but it behaves quite like a struct, I guess.