Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-6721146

type-inference from return-type not applied in conditional expressions

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Duplicate
    • Icon: P4 P4
    • 7
    • 7
    • specification
    • None
    • generic
    • generic

      The following program doesn't compile:

      import java.util.*;

      public class TestGenerics {
          List<String> test1(boolean b) {
                  return b ? Collections.emptyList() : Collections.emptyList();
          }

          List<String> test2(boolean b) {
                  if (b)
                      return Collections.emptyList();
                   else
                      return Collections.emptyList();
          }
      }

      More precisely, method test2() compiles without problem, while test1() doesn't. I think that this is the expected behaviour as it is a result of JLS 15.25 (conditional expression) and 15.12.2.8 (Inferring unconstrained type-variables). In particular, it does not seem that a ternary operator consitute an assignment context - this makes type-inference infer T=Object, thus making the RHS (List<Object> incompatible with the LHS (List<String>).

      Would it be possible to extend the JLS so to make type-inference succeed in such a setting?

            abuckley Alex Buckley
            mcimadamore Maurizio Cimadamore
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: