Monday, November 17, 2008

Java Generics and Variable Return Types

Back when I first started programming in Java, they didn't even have Generics. It was a simpler time. Admittedly, I was a freshmen in college just starting to learning Java (and programming for that matter) when Java 1.5 was released, so I really didn't understand what all the hullabaloo was about. I probably thought something along the lines of "Sweet! Now I don't have to cast when I use Vectors!"

Unfortunately my knowledge of Generics is still lacking, but I'm learning. Slowly.

Today I ran into a new problem: I wanted to a function to return a Vector of objects, but the type of object would change. So the usual solution of:

public MyClass< G > {
    public Vector< G > myAwesomeFunction() {...

fails because I don't want to have to instantiate this particular class every time I want to call that function. I searched for a long time, and could see no way to define the return type of a function when it is called. If you know how, please let me know, because it seems like it would be useful at least in this one case.

In the end I had to settle for creating a generic inner class that the function could instantiate, and then writing a function for each type that I wanted. Not ideal, but the interesting code is not duplicated as it resides in the inner class. This solution also avoids the casting fest that would occur if I just decided to have one function that returned a Vector of Objects.

On a side note, during some "research" on Generics I happened across Whitespace, a programming language which only uses, you guessed it, whitespace. All non-whitespace characters are ignored.

No comments: