Lombok: @Builder annotation lose field default value

Created on 28 Jul 2016  ·  3Comments  ·  Source: projectlombok/lombok

public class BuilderAnnotationTest {

    @Test
    public void defalutValue() throws Exception {
        assertThat(Entity.builder().build().isSingle()).isTrue();
    }
}

@Getter
@Builder
class Entity{
    private String name;
    private boolean single = true;
}

Most helpful comment

Duplicate of #916. There's a workaround

@Getter
@Builder(toBuilder=true)
@AllArgsConstructor
@NoArgsConstructor(access=AccessLevel.PRIVATE)
public class Entity {
    public static EntityBuilder builder() {
        return PROTOTYPE.toBuilder();
    }

    private static final Entity PROTOTYPE = new Entity();

    private String name;
    private boolean single = true;
}

All 3 comments

Duplicate of #916. There's a workaround

@Getter
@Builder(toBuilder=true)
@AllArgsConstructor
@NoArgsConstructor(access=AccessLevel.PRIVATE)
public class Entity {
    public static EntityBuilder builder() {
        return PROTOTYPE.toBuilder();
    }

    private static final Entity PROTOTYPE = new Entity();

    private String name;
    private boolean single = true;
}

This also works

public class BuilderAnnotationTest {

    @Test
    public void defalutValue() throws Exception {
        assertThat(new Entity().toBuilder().build().isSingle()).isTrue(); // note the "new" here
    }
}

@Getter
@Builder(toBuilder = true)
class Entity{
    private String name;
    private boolean single = true;
}

Use @Builder.Default to fix this problem.

Was this page helpful?
0 / 5 - 0 ratings