java conditional operator and different types

前端 未结 3 2153
死守一世寂寞
死守一世寂寞 2020-12-20 23:34

I have two methods in the Item Class:

public void setValue(String v);
public void setValue(Double v);

and I want to use Cond

3条回答
  •  别那么骄傲
    2020-12-21 00:07

    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.

提交回复
热议问题