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 of main
and not decided at runtime.
In fact, even though you know that the type of conditional expression is either InputStream
or String
, the compiler sees its type as Object
. From Section 15.25.3 of the Java Language Specification:
A reference conditional expression is a poly expression if it appears in an assignment context or an invocation context (§5.2. §5.3). Otherwise, it is a standalone expression.
Where a poly reference conditional expression appears in a context of a particular kind with target type T, its second and third operand expressions similarly appear in a context of the same kind with target type T.
The type of a poly reference conditional expression is the same as its target type.
The type of a standalone reference conditional expression is determined as follows:
If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.
If the type of one of the second and third operands is the null type, and the type of the other operand is a reference type, then the type of the conditional expression is that reference type.
Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2).
where lub(T1, T2)
stands for "Least Upper Bound" of types T1
and T2
. The least upper bound type of InputStream
and String
is Object
.
The expression useIsr ? inputStream : arg
is of type Object
, since that's the common type of inputStream
(InputStream
) and arg
(String
).
You don't have any opAlpha
method that accepts an Object
. Hence the compilation error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With