Why the Ternary statement does not work inside the method argument in java

I realized this in the middle of development.

Why doesn't the Ternary operator work inside the method argument? Here's obviously 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)) } } 
+5
source share
2 answers

Expression useIsr ? inputStream : arg useIsr ? inputStream : arg is of type Object , since the common types are inputStream ( inputStream ) and arg ( String ).

You do not have an opAlpha method that accepts an Object . Therefore, a compilation error.

+6
source

The compiler must decide which overloaded method should call your main method. The method call must be placed in the compiled main bytecode and not defined at run time.

In fact, although you know that the type of the conditional expression is either InputStream or String , the compiler sees its type as Object . From Section 15.25.3 Java Language Specifications :

A reference conditional expression is a poly-expression if it appears in the context of the destination or the context of the call (ยง5.2, ยง 5.3). Otherwise, it is a separate expression.

If a conditional conditional expression with a variable reference appears in the context of a certain type with the type of the target type T, its second and third expressions of the operands are similarly displayed in the context of the same type with the type of the target T.

The type of conditional conditional expression with polyregularity coincides with the type of the target type.

The type of conditional conditional expression is defined as follows:

  • If the second and third operands are of the same type (which can be a null type), then this is the conditional expression type.

  • If the type of one of the second and third operands is a null type, and the type of the other operand is a reference type, then the conditional expression type is a reference type.

  • Otherwise, the second and third operands are of types S1 and S2, respectively. Let T1 be the type that results from applying the box transform to S1, and let T2 be the type that comes from applying the box to S2 transform. The type of conditional expression is the result of applying the capture transform (ยง 5.1.10) to lub (T1, T2) .

where lub(T1, T2) stands for the "Least Highest Boundary" of types T1 and T2 . The smallest upper type of InputStream and String is Object .

+7
source

All Articles