2004-11-03

Java already has too much operator overloading for me

This caught me out this evening:

public class Quote {
public static void main(String[] args) {
int i = 10;
String s = "";
s += i + '"';
System.err.println(s);
}
}

It was less obvious what the mistake was in my real program, though, because i wasn't a convenient constant, so (i + 34) wasn't so easily recognizable.

Given that it's rare that you want to do this, and no effort to cast the char to an int, I'd really rather int + char was disallowed.

Using + for string concatenation was never the brightest of ideas. It's tricks like that, and using + to mean add on a GUI container or push_back on a sequence, or union on a set, that give operator overloading its bad name.

So it's odd to see it in a language with no user operator overloading, and it's not obvious why we should believe that it's okay for append on a string.

Interesting to see that my brain was in C++ mode here. I spelled boolean as just bool several times, and the particular mistake above looks as if I was really trying to write something more like:

std::ostringstream result;
result << i << '"';
std::cerr << result.str() << std::endl;