Comment Re:What is variance? (Score 1) 55
The variance proposal included in the JSR14 prototype also applies to arrays. This may be the alternative to current runtime-checked array covariance, that you are looking for. You can declare animals to be invariant:
In which case assigning an array of Cats to animal is a static type error:Animal[=] animals;
Or you can declare it to be covariant in a statically checked way, by writing:animals = new Cat[10];// Compile-time error!
In which case assigning elements into animals is forbidden:Animal[+] animals;
Cat[=] cats = new Cat[10];
animals = cats;
So you get to choose, at the point of declaration, whether your compiler should enforce covariance or assignability for your array variable. In both cases, absence of runtime store-check errors is guaranteed. Of course you can still read elements out of a covariant array.animals[0] = new Dog();// Compile-time error!
For completeness, let me mention that you can also have contravariant arrays types:
The contravariant array cats can hold any array into which you can insert a cat. This includes arrays of Animal, or of Object, for that matter. Contraintuitive at first, perhaps, but try thinking about it a couple of times, or run some examples using the JSR14 compiler.Cat[-] cats;
Animals[=] animals = new Animal[10];
cats = animals;// Yes, really!
cats[0] = new Cat();
Reading from a contravariant array is possible, but lets you assume nothing about what you read out:
Would this scheme be a worthy substitute for current array covariance, in your oppinion?Object o = cats[0];// OK
Cat c = cats[0];// Compile-time error!