In the following class, the return type of the two methods is inconsistent with the idea that the ternary operator:
return condition?a:b;
is equivalent to
if(condition) {
return a;
} else{
return b;
}
The first returns a Double and the second a Long:
public class IfTest {
public static Long longValue = 1l;
public static Double doubleValue = null;
public static void main(String[] args) {
System.out.println(getWithIf().getClass());// outpus Long
System.out.println(getWithQuestionMark().getClass());// outputs Double
}
public static Object getWithQuestionMark() {
return doubleValue == null ? longValue : doubleValue;
}
public static Object getWithIf() {
if (doubleValue == null) {
return longValue;
} else {
return doubleValue;
}
}
}
I can imagine this has to do with the compiler narrow casting the return type of getWithQuestionMark()
but is that language wise ok? It's certainly not what I would have expected.
Any insights most welcome!
Edit: there's very good answers below. Additionally, the following question referenced by @sakthisundar explores another side effect of the type promotion occurring in the ternary operator: Tricky ternary operator in Java - autoboxing
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…