Key Takeaways Chapter 3: Working with the Xtend Programming Language of Implementing Domain-Specific Languages with Xtext and Xtend – Second Edition

Others chapters

Chapter 3 Working with the Xtend Programming Language in Implementing Domain-Specific Languages with Xtext and Xtend – Second Edition covers what and how to use Xtend.

Basically Xtend is a concise syntax of Java. Xtend can be compiled just a Java but it’s rich on type interference, extension methods, dispatch, lambda and template expressions. In depth documentation at eclipse: https://www.eclipse.org/xtend/documentation/index.html with simple helle world example

class HelloWorld {
  def static void main(String[] args) {
    println("Hello World")
  }
}

The above Xtend can be implemented in Java like this

import org.eclipse.xtext.xbase.lib.InputOutput;
 
public class HelloWorld {
  public static void main(final String[] args) {
    InputOutput.<String>println("Hello World");
  }
}

The book prase it like this: “Xtend – a better Java with less noise”. Like the semicolons are optional. All method declarations are with def or override and they are public by default.

One major advantage is the possibility of multiline template expressions. You can’t have a multiline string in Java without using the escape character for new line. The ‘\n’. If having multiple lines for a string you’ll end up having concatenate string with plus +. Further trying to generate code nicely with indent is near impossible.

Template expression in Xtend is using french quotation marks also called angle quote «». In Eclipse you can create this when you’re inside an Xtend file with. Control + Shift + ‘<‘. That’s the key left to the letter z on a qwerty keyboard. This will create «. And including Shift you’ll get the end ».

Ctrl + <
Ctrl + Shift + <

Null-safe

Like in C#, in Xtend we have the question operator to handle null. Doing a question mark is similar to do a null-safe version.

a?.
if (a != null)

Then we come a fun naming. The Elvis operator

?:

This is similar to the C# Null coalescing operator https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator