|
Duplicate :
|
|
|
Relates :
|
|
|
Relates :
|
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?
|