Lombok: @Getter + ?: operator throws NullPointerException

Created on 6 Oct 2016  路  2Comments  路  Source: projectlombok/lombok

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;
        }
    }
}

Most helpful comment

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.

All 2 comments

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...

Was this page helpful?
0 / 5 - 0 ratings