JDK-7019649 : Syntax error for ternary operator with a generic method call as second result
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 6u23
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_7
  • CPU: x86
  • Submitted: 2011-02-15
  • Updated: 2012-09-06
  • Resolved: 2011-02-15
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
java version "1.6.0_23"
Java(TM) SE Runtime Environment (build 1.6.0_23-b05)
Java HotSpot(TM) Client VM (build 19.0-b09, mixed mode, sharing)

ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows [Version 6.1.7600]

A DESCRIPTION OF THE PROBLEM :
Ternary operator like:

Set<String> res = (flag ? other : Test.<String> genericMethod());

fails to compile. There are few conditions:
1. Ternary operator must be put into additional brackets.
2. "other" must be of type Set<String> and genericMethod defined as
 <T> Set<T> genericMethod()


STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Try to compile the attached java file.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Successful compilation
ACTUAL -
Failure to compile

ERROR MESSAGES/STACK TRACES THAT OCCUR :
Test.java:15: illegal start of expression
        Set<String> res = (flag ? Test.<String> genericMethod() : other);
                                       ^
1 error

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
import java.util.*;

public class Test{
    public static void main(String[] test){
        boolean flag = test.length % 2 == 0;
        Set<String> other = Collections.singleton("Test");

        //This compiles fine:
        print(flag ? other : Test.<String> genericMethod());

        //This failes to compile:
        print((flag ? null : Test.<String> genericMethod()));
        
        //This failes to compile:
        Set<String> res = (flag ? Test.<String> genericMethod() : other);
    }

    @SuppressWarnings({"unchecked"})
    public static <T> Set<T> genericMethod(){
        return (Set) new HashSet();
    }
    
    public static void print(Set<String> arg){
        System.out.println(arg);
    }
}

---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
Remove additional brackets or break the assignment in two lines:
Set<String> res = flag ? other : Test.<String> genericMethod();

OR

Set<String> interm = Test.<String> genericMethod();
Set<String> res = (flag ? other : interm);