Freitag, 17. Oktober 2014

Xtend - Basic Syntax Sugar

Xtend comes with a lot of syntactic sugar that makes your code more readable. In this post we will look at the basics and see how you can make your code much shorter even without learning Xtend's advanced features.

Let us take this simple snippet of Java code as an example and make it more readable step by step.

For starters, here is the 1-to-1 translation to Xtend, without using any syntax sugar.

I was serious when I said Xtend is similar to Java. Now let's remove all the small distractions: Visibility modifiers, semicolons, empty parentheses and the return keyword are all optional in Xtend. Also, since getters and setters are so widespread in Java-land, Xtend allows you to use them with the same syntax as fields.

Okay, that's a little better, but the real deal comes next. Xtend has very powerful type inference. You almost never have to write down a type if you don't want to. Xtend will even look at the control flow to infer types of earlier declarations. In our example, it can determine that the type of the Map must be <String, Person> by looking at the call to byName.put.

Another little trick up Xtend's sleeve is the use of the variable it. If you give a variable that name it becomes an implicit receiver, just like the this keyword in Java. Instead of calling, you can just call name.

Xtend also has lambdas and probably the most beautiful syntax for them. Even with the arrival of Java 8, Xtend is still easier on the eyes. Xtend allows both interfaces and abstract classes with one abstract method to be written as a lambda. Our example is much easier to express in this functional way. Exactly how Xtend manages to add new functional APIs to existing types like List will be the topic of another entry in this series.

To top it of, Xtend has literals and operators for List, Map, Set, BigInteger and BigDecimal. It will also automatically convert between Arrays and Lists. This makes these basic types much more fun to use. It even adds a few operators on top of what you know from Java, including the null-safe feature call (?.) and the elvis operator (?:) for supplying a default value. See the documentation for a full list.

This last snippet also shows how you can use a positional syntax in lambdas, when you don't want to give the parameters names. It could have alternatively been written like this:

This wraps up the basic syntax sugar of Xtend. In the upcoming posts we will look at advanced language features that allow you to write even more expressive code.