I got this noted in a middle of a development.
Why is the Ternary operator not working inside a method argument? Here it is clearly InputStream
or (else) String
.
class A{
public static boolean opAlpha(InputStream inputStream) {
// Do something
return true;
}
public static boolean opAlpha(String arg) {
// Do something else
return true;
}
public static void main(String[] args) throws Exception {
boolean useIsr = true;
InputStream inputStream = null;
String arg = null;
// boolean isTrue = useIsr ? A.opAlpha(inputStream): A.opAlpha(arg); // This is OK.
boolean isTrue = A.opAlpha(useIsr ? inputStream : arg); // This is not. (Error : The method opAlpha(InputStream) in the type A is not applicable for the arguments (Object))
}
}
The compiler needs to decide which overloaded method it should call in your
main
method. The method call must be placed in the compiled bytecode ofmain
and not decided at runtime.In fact, even though you know that the type of conditional expression is either
InputStream
orString
, the compiler sees its type asObject
. From Section 15.25.3 of the Java Language Specification:where
lub(T1, T2)
stands for "Least Upper Bound" of typesT1
andT2
. The least upper bound type ofInputStream
andString
isObject
.The expression
useIsr ? inputStream : arg
is of typeObject
, since that's the common type ofinputStream
(InputStream
) andarg
(String
).You don't have any
opAlpha
method that accepts anObject
. Hence the compilation error.