Additional operators
Besides standard operators, Xtend has additional operators that help to keep the code compact.
Quite often, you will have to check whether an object is not null before invoking a method on it; otherwise, you may want to return null
or simply perform no operation. As you will see in DSL development, this is quite a recurrent situation. Xtend provides the operator "?.
", which is the null-safe version of the standard selection operator (the dot .
). Writing o?.m
corresponds to if
(o != null) o.m
. This is particularly useful when you have cascade selections, for example, o?.f?.m
.
The Elvis operator ("?:
") is another convenient operator for dealing with default values in case of null instances. It has the following semantics: x ?: y
returns x
if it is not null
and y
otherwise.
Combining the two operators allows you to set up default values easily, for example:
// equivalent to: if (o != null) o.toString else 'default' result = o?.toString ?: 'default'
The with operator (or double...