Arrays, The Broken Parts!!

In the early days of Java and C#, both languages didn’t have generics and hence type parameters were unbound to any type and this resulted in an infinite number of class cast exceptions in our code, programmers were responsible for type checking although languages with type checkers claim to insure type safety at compile time.
Generics were introduced but arrays (the most primitive collection), stay broken. Simple example

String strings[] = {"Broken","Type", "system"};
Object objects[] = strings;
objects[0] = 69; // compiles fine, but throws ArrayStoreException at runtime

So what’s the problem here?
The problem is that arrays are covariant. This fancy word means that String[] is a subtype of Object[].

Covariant types are not bad as long as they are restricted to taking things out of the collection.

String strings[] = {"Broken","Type", "System"};
Object objects[] = strings;
Object obj =  objects[0] ; //safe

Contravariant types on the other hand are only safe for putting things in.


PECS Producer extends Consumer super is a simple rule provided by Joshua Bloch to simplify type variance

Simply put:

Set<? extends T> => Covariant
Set<? super T> =>  Contravariant 
Set<T> => Invariant

Invariant is neither  covariant nor contravariant, the exact type must match, neither the sub nor the super type are allowed

C# has better constructs for type variance, instead of using misleading keywords like extends and super, it uses in and out.

Scala on the other hand and unlike C# that copied some mistakes blindly from Java got it right. Arrays in Scala are invariant,

val a:Array[Any] = Array[String]("Better","Type","System") // does not compile

If you using a typed language, it’s very important that you understand the type variance so you don’t keep fighting with the complier.


Leave a Reply

Name and email address are required. Your email address will not be published.

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <pre> <q cite=""> <s> <strike> <strong> 

%d bloggers like this: