* Justin Dekeyser: > Then the following codes does not compile (for the same reason): > > var x = (List<Integer>) emptyList(Number.class); > List<Integer> x = (List<Integer>) emptyList(Number.class); > > incompatible types: List<Number> cannot be converted to List<Integer> > > however, the following do compile: > > var x = emptyList(Number.class); // inferred to List<Number> > List<Integer> x = emptyList(Number.class); // no mistake here, it's Integer > on the left > > Is this the expected behavior? Why does casting operation here interfere > with type inference like this?
emptyList() is special, it only works this way because the returned list is always empty, so that the element type does not matter. For any other list-returning function, the types List<Integer> and List<Number> are not interchangeable because for each type, there are operations which are not valid for the other. That's why we often need wildcards once type hierarchies are involved (List<? super Integer> or List<? extends Number>, depending on context). A somewhat similar case is functions which do not return (normally). They too can have a very general generic type which does not depend on function arguments. Thanks, Florian