libby
libby

Reputation: 634

Does Java explicitly disallow me to call a function ternary operator with multiple return type possibilities?

As demonstrated below, I have two functions who's arg types differ (String,int). I now have a third function

public void foo(String bar){}
public void foo(int bar){}
public boolean cond(){ return Math.random() > 0.5 ? true : false; }

public void runsBad(){
  String str = "";
  int i = 0;
  foo( cond() ? str : i );
}

public void runsGood(){
  if( cond() )
    foo( str );
  else
    foo( i );
}

runsGood runs without problems. However, runsBad returns the following error:

|  Error:
|  no suitable method found for foo(cond() ? str : i)
|      method foo(int) is not applicable
|        (argument mismatch; bad type in conditional expression
|            java.lang.String cannot be converted to int)
|      method foo(java.lang.String) is not applicable
|        (argument mismatch; bad type in conditional expression
|            int cannot be converted to java.lang.

Am I doing something wrong, or can Java simply not handle the ternary operator as demonstrated?

Upvotes: 0

Views: 49

Answers (2)

ardenit
ardenit

Reputation: 3890

The type of expression cond() ? str : i is neither String nor int. When you call foo with this parameter, Java tries to cast it to String (so it tries to cast i to String), but it fails. Then it tries to cast it to int (so it tries to cast str to int), but also fails. So Java can't find a method with required signature and throws an exception.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691685

Your interpretation of how the ternary expression works is incorrect. It's an expression. It's first evaluated, and the result is then passed as argument to foo().

So, instead of

if( cond() )
    foo( str );
else
    foo( i );

It's actually equivalent to

SomeCommonSuperTypeOfStringAndInt value = cond() ? str : i;
foo(value);

So this would only compile if there was a foo()method accepting a Serializable or an Object as argument.

Upvotes: 4

Related Questions