Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two methods in the Item Class:

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

and I want to use Conditional Operator to setVAlue in another class:

String str = ...
Double dbl = ...
item.setValue((condition) ? str : dbl);

but compiler says:

cannot find symbol
symbol  : method setValue(java.lang.Object&java.io.Serializable&java.lang.Comparable<? extends java.lang.Object&java.io.Serializable&java.lang.Comparable<?>>)

I think compiler uses the nearest common superclass (super interface) of Double and String as type of conditional Operator. but why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
367 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...