Cook Computing

Lambda has a link to

May 12, 2002 Written by Charles Cook

Lambda has a link to the Nice Programming Language. There is an article on Type safety in Nice which mentions covariant arrays:

In Java arrays are covariant: a String[] array can be passed to a method that expects an Object[] argument. But what happens if the method writes a Picture into the array? No error is detected at compile time. At run time, an ArrayStoreException is thrown.

This shows that arrays should not not be covariant. So why are they covariant in Java? Once again, mostly because of its limited type system. Object[] is often a poor replacement for T[] where T is a type parameter. Another reason is that covariant arrays are sometimes safe: when they are used in a read-only way.

In Nice, arrays are not covariant. Therefore run time errors like ArrayStoreException never occur. Moreover, it is still possible to use covariantly arrays while only reading from them. This require Nice's powerful type system: constrained type parameters: <java.awt.Component T> void read(T[]); can be applied to arrays whose component types are subtypes of java.awt.Component. Type checking guarantees that the array will not be written to by this method, so that there will be no run time failure.