Home > Blockchain >  Default Value for BigDecimal using Lombok Builder
Default Value for BigDecimal using Lombok Builder

Time:02-01

Let's consider the following Entity:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Audi extends Car {

    private String name;
    
    private String headquarter;
    
    private BigDecimal revenue = BigDecimal.ZERO;

    private BigDecimal totalAssets = BigDecimal.ZERO;

}

I want to have all BigDecimal variables with BigDecimal.ZERO as default value. If I initialize it immediately after declaration,

I got this warning:

@Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final.

For an Entity with 10/15 BigDecimal, it's not so beautiful to have this annotation on each field.

Any alternative?

CodePudding user response:

As Michael pointed out, you don't have many other options. If you've added the @Builder annotation, you must use @Builder.Default for each field in order to utilize the fluent builder API.

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Audi extends Car {

    private String name;
    private String headquarter;
    @Builder.Default
    private BigDecimal revenue = BigDecimal.ZERO;
    @Builder.Default
    private BigDecimal totalAssets = BigDecimal.ZERO;
}

Usage:

Audi audi = Audi.builder()
    .name("Audi A3")
    .headquarter("Germany")
    .build();
System.out.println(audi);

Output:

Audi(name=Audi A3, headquarter=Germany, revenue=0, totalAssets=0)

If builder functionality is not needed, objects can be instantiated in the traditional Java way using a constructor. However, in this case, the @Builder annotation should be removed and default values must be set directly in the constructor or during declaration.

@Data
@NoArgsConstructor
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Audi extends Car {
    @NonNull
    private String name;
    @NonNull
    private String headquarter;
    private BigDecimal revenue = BigDecimal.ZERO;
    private BigDecimal totalAssets = BigDecimal.ZERO;
}

Usage:

final Audi audi = new Audi("Audi A3", "Germany");
System.out.println(audi);

Output:

Audi(name=Audi A3, headquarter=Germany, revenue=0, totalAssets=0)
  • Related