22
@Data
public abstract class B {
   private final String str;
}

@Data
public class A extends B{
   private final String s;
}

Data on class A complains in intellij, but the codes can get compiled successfully through command line, not sure what to do

Richard
  • 223
  • 1
  • 2
  • 5

3 Answers3

22

One problem is that @Data is meant for mutable data and there's nothing mutable in your classes. So using @Data is simply wrong... and whether it compiles or not doesn't really matter.

If you want mutable data, then remove the final field. For immutable data, make all fields final and use @Value. Sometimes, partially mutable data is needed, but I try hard to avoid it as it's confusing (some fields can be set, some can't) and they provide disadvantages of both.


The other problem is that Lombok can't access class hierarchies. With B having a final field, you need it to be initialized in the constructor, which means that A's constructor has to call a non-default constructor. This isn't possible with Lombok. There's @Superbuilder in Lombok, which is about the only feature of Lombok dealing well with class hierarchies.

maaartinus
  • 44,714
  • 32
  • 161
  • 320
9

The @Data annotation does not add a default contructor. Try to add a @NoArgsConstructor to your Base Class B to generate a default constructor with Lombok.

You can also read up what @Data actually means here.

jdickel
  • 1,437
  • 1
  • 11
  • 21
  • but @NoArgsConstructor will still search for constructor, but class B is abstract. And also why is it good when I compile it using cmd? – Richard Sep 04 '19 at 21:43
  • And maybe initialize the constant field in this constructor? Or that's not required for IntelliJ to calm down? – 1737973 Sep 05 '19 at 00:22
  • @Richard this has nothing to do with the compiler. It will also compile in IntelliJ. But if you have a private final field which is not initialized, then it’s only possible to set it once in it’s own class. Since the class itself is abstract you can only set it in the default constructor as uprego already mentioned. (Maybe write the contructor by hand or initialize it directly at the declaration). Otherwise you will get a run time exception when using the final attribute since it never got initialized. Does that make sense to you? – jdickel Sep 05 '19 at 08:59
7

This does not event compile. In Intellij, when you are not sure what is the problem with lombok code, you can open class in which you are unsure, go on Refactor -> Delombok -> All lombok annotations and you will see what lombok actually create for you.

Spasoje Petronijević
  • 1,476
  • 3
  • 13
  • 27