I'm wondering is there any way to combine java record with lombok's @Builder.Default?
Let's consider an example with properties object for new file creation.
Before java 14
@Value
@Builder
public class FileProperties {
@Builder.Default
String directory = System.getProperty("user.home");
@Builder.Default
String name = "New file";
@Builder.Default
String extension = ".txt";
}
Java 14
@Builder
public record FileProperties (
String directory,
String name,
String extension
) {}
But in case if I try to use something like
@Builder
public record FileProperties (
@Builder.Default
String directory = System.getProperty("user.home")
) {}
Compiler will fail with an error, revealing that such syntax is not allowed. Do we have any solution to this problem?
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With