Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

java conditional operator and different types

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...