0

I was using ternary if like in example:

carDto.setTireId(car.getTire() == null ? null : car.getTire().getId());

It was causing NullPointer exception. I did not understand why, but then I noticed that setTireId expects integer as parameter. So when I changed to

carDto.setTireId(car.getTire() == null ? 0 : car.getTire().getId());

everything started working as expected.

When I tried

carDto.setTireId(null);

I got compilation exception as expected.

My question is: why is the first statement not failing at compile time? In this case it was simple human error, but it could make a hard-to-find bug.

Heisenberg
  • 3,153
  • 3
  • 27
  • 55
  • Check if car is null. `(car != null ? (car.getTire() != null ? car.getTire().getId() : null) : new Car())`. Can you post the sources of your classes? – Jared Burrows Jul 13 '15 at 18:33
  • 2
    @Marco13 How I could have missed it. Thanks! Closing the question. – Heisenberg Jul 13 '15 at 18:34
  • @JaredBurrows actually read his question. He's not asking how to write the ternary expression as he already figured it out, but asking why a particular line doesn't fail at compile time. – d0nut Jul 13 '15 at 18:34

0 Answers0