lombok: 1.16.10
java: Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)
?: throws NullPointerException. if/else doesn't throw it. Why?)
public class LombokTest {
public static void main(String[] args) {
Car c = new Car();
System.out.println(c.getPowerCorrect());
System.out.println(c.getPowerNullPointerException());
}
@Getter
@AllArgsConstructor
public static class Engine {
private int power;
}
@Getter
@NoArgsConstructor
public static class Car {
private Integer power;
private Engine engine;
public Integer getPowerCorrect() {
if (engine != null) {
return engine.getPower();
} else {
return power;
}
}
public Integer getPowerNullPointerException() {
return (engine != null) ? engine.getPower() : power;
}
}
}
That's not a lombok issue, it's an interpretation type issue.
you had defined Integer power; in Car, but in Engine is defined as int power; java is using the more specific type which is int to parse the value and when it find null... well, you know the history.
you must use same type for both or slipt it in an if/else block.
Looks like it's not specificity question. It casts to first expression type (engine.getPower()). If engine.getPower() will return Integer and power will be int it will work...
Most helpful comment
That's not a lombok issue, it's an interpretation type issue.
you had defined
Integer power;inCar, but inEngineis defined asint power;java is using the more specific type which isintto parse the value and when it findnull... well, you know the history.you must use same type for both or slipt it in an
if/elseblock.