List l; // The List-object we are working on.
int sum = 0; // Contains the sum after the loop.
boolean proceed = true;
while (proceed) {
if (l instanceof Nil)
proceed = false;
else if (l instanceof Cons) {
sum = sum + ((Cons) l).head; // Type cast!
l = ((Cons) l).tail; // Type cast!
}
}
The advantage of this code is that it can be written without touching the classes Nil and Cons. The drawback is that the code constantly uses type casts and instanceof to determine what class of object it is considering.