Because to do anything else wouldn't make any sense. The ternary conditional operator must return some value of some specific type -- all expressions must result in a specific type at compile time. Further, note that overload resolution happens at compile time, as well. The behavior you are trying to invoke here (late binding) doesn't exist in this form in Java.
The type of the expression must be compatible with the true and false subexpressions. In this case, the nearest common ancestor class is Object
, and you don't have a setValue(Object)
overload.
This is the simplest way to rewrite what you have in a working way:
if (condition) {
item.setValue(str);
} else {
item.setValue(dbl);
}
You could also provide a setValue(Object)
overload that inspects the type of object passed and delegates to the appropriate setValue()
overload, throwing an exception if the type is not acceptable.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…