Search code examples
javanullpointerexceptionlombokintellij-lombok-plugin

using lombok builder with an abstract class


I have this abstract class:

public abstract class Hotel {

     protected List<String> defaultValues() {
        return List.of("Geeks", "For", "Geeks");
    }
}

and this lombok class that extends from the abstract class:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class Hostel extends Hotel {         
    private List<String> values = defaultValues();    

    @SuppressWarnings("unused")
    public static class HosteBuilder {

        public Hostel build() {    
            this.values.add("ww");    
            ...
        }
    }    
}

but I get a nullpointer in the line values.add("ww");


Solution

  • The Builder class needs to create a new instance first. But also, the list you are using is Immutable. Both these issues have been noted by user Michael. In any case, lombok is not to blame for any of this, as it only adds methods, none of which you are using in your example.

    First, change the list to a mutable list type:

    return Arrays.asList(new String[]{"Geeks", "For", "Geeks"});
    

    And the extending type to:

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @EqualsAndHashCode
    public class Hostel extends Hotel {         
        private List<String> values = defaultValues();    
    
        @SuppressWarnings("unused")
        public static class HosteBuilder {
    
            public Hostel build() {
                Hostel hostel = new Hostel();
                hostel.values.add("ww");    
                // ...
                return hostel;
            }
        }    
    }