You can achieve the same outcome not by @Builder.Default but by defining the builder itself with defaults for Lombok:
@Builder
public record FileProperties (
String directory,
String name,
String extension
) {
public static class FilePropertiesBuilder {
FilePropertiesBuilder() {
directory = System.getProperty("user.home");
name = "New file";
extension = ".txt";
}
}
}
Then to test it:
public static void main(String[] args) {
System.out.println(FileProperties.builder().build());
}
Output:
FileProperties[directory=/home/me, name=New file, extension=.txt]
Answer from user21063779 on Stack OverflowYou can achieve the same outcome not by @Builder.Default but by defining the builder itself with defaults for Lombok:
@Builder
public record FileProperties (
String directory,
String name,
String extension
) {
public static class FilePropertiesBuilder {
FilePropertiesBuilder() {
directory = System.getProperty("user.home");
name = "New file";
extension = ".txt";
}
}
}
Then to test it:
public static void main(String[] args) {
System.out.println(FileProperties.builder().build());
}
Output:
FileProperties[directory=/home/me, name=New file, extension=.txt]
Don't use a record if you want to do more things than recording values in a container. In this case you shouldn't use a record because it doesn't allow you to instruct something different than simple recording your arguments.
If you want a default value for any instance you are creating of this class you need a "normal" constructor.
That's why you can't set values (again) in records.
Is it worth using the Builder pattern with Java Records, or does it defeat the purpose of using Records in the first place? I'm trying to decide if I should combine these two, especially for scenarios where I have optional fields. Any advice or best practices?
Records and @Builder
ANN: Record Builder – Builder and Withers for Java 16 Records
I've mentioned this here before but now that Java 16 is released I've made a new release compiled with the latest Java 16.
Java 16 introduces Records. While this version of records is fantastic, it's currently missing some important features normally found in data classes: a builder and "with"ers. This project is an annotation processor that creates:
-
a companion builder class for Java records
-
an interface that adds "with" copy methods
-
an annotation that generates a Java record from an Interface template