Search code examples
javaeclipsehudson

inconvertible types but without warning or error?


During some code review I found this line of code:

ScTyp lScTyp = (ScTyp) (lWorkspace.getScTyp() == null ? ChartFactory.BLANK_STRING : lWorkspace.getScTyp());

I was a little bit confused becouse this line of code leads to a failed Hudson build in the regarding project. Reason: inconvertible types

I know that the typecast is completly wrong here. If getScTyp() is null it would try to cast a String (ChartFactory.BLANK_STRING) into ScTyp.

Why doesnt Eclipse show an error or at least a warning in this line of code?


Solution

  • Since the ternary operator can evaluate to either a String or what getScType returns, it gets evaluated to an Object reference. It is perfectly alright to cast an Object reference to any other type.

    Another way to view that line would be

    Object temp = lWorkspace.getScTyp() == null ? ChartFactory.BLANK_STRING : lWorkspace.getScTyp();
    ScTyp lScTyp = (ScTyp)temp;
    

    If Both paths through the ternary operator returned ScTyp, then there would have been no need for a cast.

    I'm guessing Eclipse originally did display an error before the cast was added, and someone fixed the error by adding the cast. That then hid the real error.