Java quiz of the day (easy): what gives
Object[] a = new Integer[]{};
List<Object> b = new ArrayList<Integer>();
Response: we get an exception on the second line:
Type mismatch: cannot convert from ArrayList<Integer> to List<Object>
Arrays and Generics are not consistent. While for arrays, an array of some type is also an array of one of its parent types, the same is not true for Generics. If it was, we could construct weird things where we would get at most a runtime exception when trying to access items of a collection. See the following example:
class A{
void foo(List list) {
List
Here line (A) is not a legal assignment. If it was, then we could insert into our originally List
Check out Scala’s co- and contravariance features => Very handy to get things like above working!
Yes it is beautifully solved in Scala. The ability to define the co- and contravariance with respect to Generic type directly at the definition point is clever.