I really like the addition of records in Java 14, at least as a preview feature, as it helps to reduce my need to use lombok for simple, immutable "data holders". But I'm having an issue with the implementation of nullable components. I'm trying to avoid returning null
in my codebase to indicate that a value might not be present. Therefore I currently often use something like the following pattern with lombok.
@Value
public class MyClass {
String id;
@Nullable String value;
Optional<String> getValue() { // overwrite the generated getter
return Optional.ofNullable(this.value);
}
}
When I try the same pattern now with records, this is not allowed stating incorrect component accessor return type
.
record MyRecord (String id, @Nullable String value){
Optional<String> value(){
return Optional.ofNullable(this.value);
}
}
Since I thought the usage of Optional
s as return types is now preferred, I'm really wondering why this restriction is in place. Is my understanding of the usage wrong? How can I achieve the same, without adding another accessor with another signature which does not hide the default one? Should Optional
not be used in this case at all?
record MyRecord (String id, Optional<String> value) {}
? – CoastalOptional
is not to use them as arguments or members though. – Mitingercreate()
method above. – CoastalOptional
inrecord
s and it was the right choice from a reliability, readability and maintenance perspective. – Roarke