-
Enhancement
-
Resolution: Duplicate
-
P4
-
7
-
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?
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?
- duplicates
-
JDK-4879776 Constructor type inference (JSR14 + JSR65 ++)
-
- Closed
-
- relates to
-
JDK-6404665 14.11: spec for switch doesn't allow wildcard of wrapper or enum
-
- Open
-
-
JDK-6721089 ternary conditional operator does not handle generics
-
- Resolved
-