https://www.youtube.com/watch?v=2EL9lUfd9tI
Overview
record (double lon, double lat) {}
- You get the following for free
- constructor
- getters
- equal
- string
- hashcode
- Other Benefits
- records are immutable - less code, no need to write
final
Extensibility
- Records cannot be extended. Not can they extend another Record.
- Records, however can implement interfaces
- This is a sensible restriction
Compact Constructor
record Location(double lon, double lat) {
public Location {
// Validation
// Cleaning
lon = Math.round(lon * 100.00 / 100.00)
}
}
- The Compact constructor is a way to declare a transformer or a map function for a record.
- It lets you add validation and transform statements.
- At first glance, it may appear to be a constructor, but it isn’t. It is the function that is called preceding the constructor.
- If you declare a non-canonical constructor that calls the canonical constructor, the compact constructor will be called twice. This may need clarification, but it is good to know if you are changing state or implementing code with side effects in the compact constructor.
Tuples
- Java Records can also be used as Tuples.
- This can make the language very expressive when having to deal with streams.
Q&A
- Why not use Lomblok?
- Records are a language feature and will behave cohesively with other parts of the language, such as pattern matching.
- Everybody may not use library code, which creates a dependency on something that may not be maintained.