Thursday, September 17, 2009

Hey Scala, Where's My Ternary Operator?

While still playing around with Scala Hello World programs, I thought I'd do a little Java integration test so I wrote this awesome program:
println(Math.random() > 0.5 ? "Hello World!" : "Goodbye World")

The result, of course, was neither "Hello World!" nor "Goodbye World" (lest this be a very short blog), but...
error: identifier expected but string literal found

Huh? Why wouldn't that work? Is there no ternary operator? How primitive!

Of course, it dawned on me without too much more wasted neurons: this is a functional language - everything returns a value! (It has been some time, but the memories are slowly starting to come back.) So, of course, it only makes sense that if/else returns a value as well. Voila:

println(if (java.lang.Math.random() > 0.5) "Hello World!"
else "Goodbye World")

And once you see it, you see how obvious it is - that this is just the way if/else should work. Why should any language need a quirky ternary operator when they all have a perfectly good if/else construct already?

On a related note, I'm feeling an increasing annoyance as I look at Java code at work all day. For example, today I was looking at code that essentially did this:

public List convert(List customers) {
ArrayList dtos = new ArrayList();
for (Customer c : customers) {
dtos.add(convert(c));
}
return dtos;
}

public CustomerDTO convert(Customer c) {
return new CustomerDTO(c.getCustomerId(), c.getName(), c.getBalance());
}


So, as soon as I saw that, I thought, "Man, if we were using Scala, I'd just have to write this:"
def convert(customers : List[Customer]) =
customers.map(c => new CustomerDTO(c.customerId, c.name, c.balance))

In fact, the expression is so short, you most likely wouldn't even bother to put it in a function. (Except to test it, or mock it.)

The brevity here isn't just "cool" (even though it is). This is an extremely simple piece of code; and an extremely common operation. The brevity of the Scala code helps to express how simple the function is, whereas the Java code for the same operation takes longer to read and could leave you wondering whether there was something you missed.

The most ridiculous thing about this comparison is that Java has been around for almost 15 years now! And still we have to write 5 lines of code to do ridiculously simple operations like this. I can't imagine it would be much work at all for a few smart guys to add the functionality that Scala displays here to Java, but it appears more and more that Java is slowing to a halt under its own sheer weight and the burden of keeping 6 million-odd developers happy. (As if writing the above code over and over again is the way to do it.)

R.I.P. Java?

No comments:

Post a Comment