Post fix
It works again!
@Builder
public record MyRecord(String myField) {
}
Pre fix
It was a known IntelliJ bug. There was, however, a workaround:
public record MyRecord(String myField) {
@Builder public MyRecord {}
}
Important: Once you insert the @builder inside the record, you must remove the @builder above it
Post fix
It works again!
@Builder
public record MyRecord(String myField) {
}
Pre fix
It was a known IntelliJ bug. There was, however, a workaround:
public record MyRecord(String myField) {
@Builder public MyRecord {}
}
Important: Once you insert the @builder inside the record, you must remove the @builder above it
According to this, records are supported from Lombok version v1.18.20
@Builderon records is supported since the last release v1.18.20. Which version are you using?Note that this may also be just an IDE issue. If you are using IntelliJ, it may not be supported, yet.
Probably an IntelliJ issue. Try writing the code without IntelliJ auto-complete, see if it compiles. If it does, it's an IntelliJ issue; if it does not, something is wrong with your code.
[BUG] @lombok.Builder.Default does not work on records
Java Records and Lombok annotation - IntelliJ - Stack Overflow
InnerBuilder, an IntelliJ IDEA plugin that adds a 'Builder' action to the Generate menu (Alt+Insert) which generates an inner builder class as described in Effective Java.
lombok - Java Record with @Builder.Default - Stack Overflow
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.
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?
