dagblog.
← Archive

Syntactic sugar in Java 7


Fancy a little syntactic sugar? Or perhaps not?

Like other languages, Java has gone down the road of adding syntactic sugar. From what’s been published, version 7 looks likely to keep that trend going. One thing these sweeteners have in common is that they split the community in two. Some people welcome them with open arms. Others can’t stomach them.

Collections

Initialize collections (lists and maps) using the syntax for array literals. Unsure what I mean? The code below will show you.

//Java 6 a starší
List polehouni = new ArrayList();
polehouni.add("Dagi");
polehouni.add("NkD");
polehouni.add("Roumen");
//Java 7
List polehouni = ["Dagi", "NkD", "Roumen"];

nebo

List polehouni = new ArrayList() ["Dagi", "NkD", "Roumen"];

For a map it might look like this.

//Java 7
Map = ["Abba" : 1972, "Beatles" : 1960, "Corrs" : 1995];

Operators

Overload arithmetic operators for BigDecimal and BigInteger.

//Java 6 a starší
BigInteger c;
BigInteger a = new BigInteger(1);
BigInteger b = new BigInteger(1);
c = a.add(b);
//Java 7
BigInteger c;
BigInteger a = new BigInteger(1);
BigInteger b = new BigInteger(1);
c = a + b;

Properties

The proposed changes concern how bean properties are accessed and defined.

//Java 6 a starší
public class Auto {
private int barva;

public void setBarva(int barva) {
this.barva=barva;
}

public int getBarva() {
return this.barva;
}
}
//Java 7
public class Auto {
public int property barva;
}

Accessing individual properties would use a special symbol (., #, or ->) in place of the getter or setter name.

//Java 6 a starší
Auto auto = new Auto();
auto.setBarva(10);
int barva = auto.getBarva();
//Java 7
Auto auto = new Auto();
auto->barva = 10;
int barva = auto->barva;

Closures

A new data type, the function. It would replace anonymous inner classes. Read more in the earlier article Closures in Java — Functions Revolt.

As I said, nobody is indifferent to these changes. They haven’t all been approved, and most of the sweeteners above are still proposals. They may never make it into Java 7. I’d welcome declaring collections as shown above, for instance, but in general I’m no fan of extending the syntax.

In the past there were two main arguments against extending the syntax. As of Java 6, there are three.

  1. It breaks source-code backward compatibility.
  2. It makes syntax harder to read (exceptions introduce a new dimension).
  3. The JVM already supports other languages that can offer this kind of improvement.

I understand why Java’s developers want to keep the syntax competitive. Still, why not let the scripting languages on the JVM fight this particular battle?

Related articles

Medium version

Related articles

Related CZ Podcast episodes