Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!

 



Forgot your password?
typodupeerror

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:
Animal[=] animals;
In which case assigning an array of Cats to animal is a static type error:
animals = new Cat[10]; // Compile-time error!
Or you can declare it to be covariant in a statically checked way, by writing:
Animal[+] animals;
Cat[=] cats = new Cat[10];
animals = cats;
In which case assigning elements into animals is forbidden:
animals[0] = new Dog(); // Compile-time error!
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.

For completeness, let me mention that you can also have contravariant arrays types:

Cat[-] cats;
Animals[=] animals = new Animal[10];
cats = animals; // Yes, really!
cats[0] = new Cat();
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.

Reading from a contravariant array is possible, but lets you assume nothing about what you read out:

Object o = cats[0]; // OK
Cat c = cats[0]; // Compile-time error!
Would this scheme be a worthy substitute for current array covariance, in your oppinion?

Slashdot Top Deals

Can't open /usr/games/lib/fortunes.dat.

Working...