"I have a mind like a steel... uh... thingy." Patrick Logan's weblog.

Search This Blog

Saturday, August 12, 2006

Java Varargs Puzzle

Richard Bair puzzles over a scenario using Java 5 varargs...

The problem is that (Object)null tells the compiler to include a one element Object array where the first element is null. Instead, what we wanted to do was this (Object[])null! This is why we get the compiler warning, the compiler doesn't know if we want null to be an element in the vararg array or whether we want it to be the vararg array itself.
I would have expected that passing null to be interpreted as passing one Object, which is null. Strange that null has to be cast to Object though.

But then passing an Object array that is null means "don't pass anything"? This is just puzzling. It should be wrong... an artifact of a not-quite-object-oriented language with too much "magic".

To express "don't pass anything" I would expect to invoke the method like this...

elementCount()
...i.e. don't pass anything.

I would expect a null cast as an Object array to mean the same thing as a null cast to an Object. An Object array should be an Object, in an object-oriented language. No matter how you cast a null argument, it should be interpreted as one argument passed to the method. Instead the meaning changes on how the null is cast, or whether it is cast at all.

Unfortunately as well, invoking the method with no args means an implicit new of an empty Object array, as opposed to a null cast as an Object array. I guess I need to fire up the computer that has Java 5 on it and see it for myself.

Confusing. These idiosyncracies will cause someone, somewhere, a sleepless night every now and then.

1 comment:

Anonymous said...

it semplifies a lot of the design of the varargs receiving code, so you doens't have to check for null on varargs

Blog Archive

About Me

Portland, Oregon, United States
I'm usually writing from my favorite location on the planet, the pacific northwest of the u.s. I write for myself only and unless otherwise specified my posts here should not be taken as representing an official position of my employer. Contact me at my gee mail account, username patrickdlogan.