I am currently replacing all my standard POJO's to use Lombok for all the boilerplate code. I find myself keeping getters for lists because I want to return an empty list if the list has not been initialized. That is, I don't want the getter to return null. If there some lombok magic that I'm not aware of that can help me avoid doing this?
Example of generated code
private List<Object> list;
public Object getList(){ return list; }
What I would like instead:
private List<Object> list;
public Object getList(){
if (list == null) {
return new ArrayList();
}
return list;
}
You can achieve this by declaring and initializing the fields. The initialization will be done when the enclosing object is initialized.
private List<Object> list = new ArrayList();
Lomboks @Getter
annotation provides an attribute lazy
which allows lazy initialization.
@Getter(lazy=true) private final double[] cached = expensiveInitMethod();