Using both @AllArgsConstructor and @RequiredArgsConstructor

1,503 views
Skip to first unread message

Troy

unread,
Sep 12, 2017, 4:36:45 PM9/12/17
to Project Lombok
I have a class which looks like this:

    @RequiredArgsConstructor
   
@AllArgsConstructor
   
@FieldDefaults(level=AccessLevel.PRIVATE, makeFinal=true)
   
enum Foo {

     A
("a", "A"),
     B
("b);


      @NonNull String first;
      String second;
    }



The first argument is required.  The second is optional.  Is there a way to generate both constructors? As shown, RequiredArgsConstructor generates a two-argument constructor, because there is not value provided in the definition of second, which duplicates the AllArgsConstructor constructor.  If I instead declared second by

String second = null;

then both annotations generate a one arg constructor (for first).  

Martin Grajcar

unread,
Sep 12, 2017, 4:54:36 PM9/12/17
to project...@googlegroups.com
I guess, you consider it being optional, because of its nullability, but this is not how Lombok sees it. Both arguments are required because of makeFinal=true. Any field which is @NonNull or final counts as required for Lombok. You'd need a NonNullArgsConstructor, which does not exist.

This could be useful sometimes, but I doubt such a FR would get accepted. With enums, I often have something like

Z(),
A("a1"),
B("b1", "b2"),
C("c1", "c2", "c3"),

where I need many constructors and I have to write them manually (which is, fortunately, easy). Default arguments would help, but it's getting pretty complicated for not so much gain.

As a side note, I'd suggest using the empty string instead of null, if possible.




--
You received this message because you are subscribed to the Google Groups "Project Lombok" group.
To unsubscribe from this group and stop receiving emails from it, send an email to project-lombok+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages