blob: af0a9a82c307c6682eb7642edd92788459312c14 [file] [log] [blame]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Xtend - Expressions</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description"
content="Xtend is a statically typed programming language sitting on top of Java.">
<meta name="author" content="Sven Efftinge">
<meta name="author" content="Miro Spoenemann">
<!-- styles -->
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="/xtend/images/favicon.png">
<link href="/xtend/css/bootstrap.css" rel="stylesheet" type='text/css'>
<link href="/xtend/css/bootstrap-responsive.css" rel="stylesheet" type='text/css'>
<link href="/xtend/css/shield-responsive.css" rel="stylesheet" type='text/css'>
<link href='/xtend/css/fonts.css' rel='stylesheet' type='text/css'>
<link href="/xtend/css/prettyPhoto.css" rel="stylesheet" media="screen" type='text/css'>
<link href="/xtend/css/prettify.css" type="text/css" rel="stylesheet"/>
<link href="/xtend/css/style.css" rel="stylesheet" type='text/css'>
<!--[if lt IE 9]>
<link href="css/iebugs.css" rel="stylesheet" type='text/css'>
<![endif]-->
<!-- BEGIN Cookie Consent
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.3/cookieconsent.min.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.3/cookieconsent.min.js"></script>
<script>
window.addEventListener("load", function(){
window.cookieconsent.initialise({
"palette": {
"popup": {
"background": "#000"
},
"button": {
"background": "#f1d600"
}
},
"theme": "edgeless",
"type": "opt-in",
onInitialise: function (status) {
var type = this.options.type;
var didConsent = this.hasConsented();
if (type == 'opt-in' && didConsent) {
// TODO: enable cookies
}
if (type == 'opt-out' && !didConsent) {
// TODO: disable cookies
}
},
onStatusChange: function(status, chosenBefore) {
var type = this.options.type;
var didConsent = this.hasConsented();
if (type == 'opt-in' && didConsent) {
// TODO: enable cookies
}
if (type == 'opt-out' && !didConsent) {
// TODO: disable cookies
}
},
onRevokeChoice: function() {
var type = this.options.type;
if (type == 'opt-in') {
// TODO: disable cookies
}
if (type == 'opt-out') {
// TODO: enable cookies
}
},
"content": {
"href": "http://www.eclipse.org/legal/privacy.php"
}
})});
</script>
END Cookie Consent -->
</head>
<body>
<!-- Navbar -->
<div class="navbar navbar-fixed-top"
style="border-bottom: 1px solid #000;">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse"
data-target=".nav-collapse"> <span class="icon-bar"></span> <span
class="icon-bar"></span> <span class="icon-bar"></span>
</a> <a class="brand" href="/xtend/index.html"></a>
<div class="nav-collapse collapse" style="height: 0px;">
<ul class="nav">
<li ><a href="/xtend/download.html">Download</a></li>
<li ><a href="/xtend/documentation/index.html">Documentation</a></li>
<li ><a href="/xtend/community.html">Community</a></li>
<li ><a href="http://xtext.org">Xtext</a></li>
<li ><a href="http://www.eclipse.org">Eclipse.org</a></li>
</ul>
<!--div class="btn-group pull-right">
<div class="g-plusone" data-href="http://www.xtend-lang.org"></div>
</div-->
</div>
<!--/.nav-collapse -->
</div>
</div>
</div>
<!-- Navbar End -->
<div class="page-content">
<script>
function startSearch(event) {
if (event.keyCode == 13) {
var q = 'site:eclipse.org/xtend/documentation+' + event.target.value;
window.open('https://www.google.com/search?q=' + q, "_self");
}
}
</script>
<div class="wrapper">
<div id="page">
<div class="inner">
<div id="maincontainer" class="container">
<span class="edit-on-github pull-right">
<a href="https://github.com/eclipse/xtext/edit/website-published/xtend-website/documentation/203_xtend_expressions.md">Edit on Github</a>
</span>
<div class="span3" style="margin-left: 0px;">
<div class="search-bar">
<img src="/xtend/images/search-gray.png"/>
<input type="search" id="google-search" onkeyup="startSearch(event);"/>
</div>
<ul id="nav-outline">
<li>&nbsp;</li>
<li style="color : #333;">Getting Started</li>
<li><a href="101_gettingstarted.html">Hello World</a></li>
<li><a href="102_moviesexample.html">The Movies Example</a></li>
<li>&nbsp;</li>
<li style="color : #333;">Reference Documentation</li>
<li><a href="201_types.html">Java Interoperability</a></li>
<li><a href="202_xtend_classes_members.html">Classes and Members</a></li>
<li><a href="203_xtend_expressions.html">Expressions</a></li>
<li><a href="204_activeannotations.html">Active Annotations</a></li>
</ul>
</div>
<div class="span9 doc-contents">
<h1 id="xtend-expressions">Expressions</h1>
<p>In Xtend everything is an expression and has a return type. Statements do not exist. That allows you to compose your code in interesting ways. For example, you can have a <code>try catch</code> expression on the right hand side of an assignment:</p>
<pre><code class="language-xtend">val data = try {
fileContentsToString('data.txt')
} catch (IOException e) {
'dummy data'
}
</code></pre>
<p>If <code>fileContentsToString()</code> throws an <a href="http://docs.oracle.com/javase/8/docs/api/java/io/IOException.html">IOException</a>, it is caught and the string <code>'dummy data'</code> is assigned to the value <code>data</code>. Expressions can appear as <a href="202_xtend_classes_members.html#fields">initializers of fields</a>, the body of constructors or methods and as values in annotations. A method body can either be a <a href="203_xtend_expressions.html#blocks">block expression</a> or a <a href="203_xtend_expressions.html#templates">template expression</a>.</p>
<h2 id="xtend-expressions-literals">Literals</h2>
<p>A literal denotes a fixed, unchangeable value. Literals for <a href="203_xtend_expressions.html#string-literals">strings</a>, <a href="203_xtend_expressions.html#number-literals">numbers</a>, <a href="203_xtend_expressions.html#boolean-literal">booleans</a>, <code>null</code> and <a href="203_xtend_expressions.html#type-literal">Java types</a> are supported as well as literals for unmodifiable collection types like lists, sets and maps or literals for arrays.</p>
<h3 id="string-literals">String Literals</h3>
<p>A string literal is of type <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html">String</a>. String literals are enclosed in a pair of single quotes or double quotes. Single quotes are more common because the signal-to-noise ration is better, but generally you should use the terminals which are least likely to occur in the string value. Special characters can be quoted with a backslash or defined using unicode notation. Contrary to Java, strings can span multiple lines.</p>
<pre><code class="language-xtend">'Hello World !'
"Hello World !"
'Hello "World" !'
"Hello \"World\" !"
"Hello
World !"
</code></pre>
<h3 id="character-literals">Character Literals</h3>
<p>Character literals use the same notation as String literals. If a single character literal is used in a context where a primitive <code>char</code> or the wrapper type <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Character.html">Character</a> is expected, the compiler will treat the literal as such a value or instance.</p>
<pre><code class="language-xtend">val char c = 'c'
</code></pre>
<h3 id="number-literals">Number Literals</h3>
<p>Xtend supports roughly the same number literals as Java with a few differences. First, there are no signed number literals. If you put a minus operator in front of a number literal it is treated as a <a href="203_xtend_expressions.html#operators">unary operator</a> with one argument (the positive number literal). Second, as in Java 7, you can separate digits using <code>_</code> for better readability of large numbers. An integer literal creates an <code>int</code>, a <code>long</code> (suffix <code>L</code>) or a <a href="http://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html">BigInteger</a> (suffix <code>BI</code>). There are no octal numbers</p>
<pre><code class="language-xtend">42
1_234_567_890
0xbeef // hexadecimal
077 // decimal 77 (*NOT* octal)
-1 // an expression consisting of the unary - operator and an integer literal
42L
0xbeef#L // hexadecimal, mind the '#'
0xbeef_beef_beef_beef_beef#BI // BigInteger
</code></pre>
<p>A floating-point literal creates a <code>double</code> (suffix <code>D</code> or none), a <code>float</code> (suffix <code>F</code>) or a <a href="http://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html">BigDecimal</a> (suffix <code>BD</code>). If you use a <code>.</code> you have to specify both, the integral and the fractional part of the mantissa. There are only decimal floating-point literals.</p>
<pre><code class="language-xtend">42d // double
0.42e2 // implicit double
0.42e2f // float
4.2f // float
0.123_456_789_123_456_789_123_456_789e2000bd // BigDecimal
</code></pre>
<h3 id="boolean-literal">Boolean Literals</h3>
<p>There are two boolean literals, <code>true</code> and <code>false</code> which correspond to their Java counterpart of type <code>boolean</code>.</p>
<h3 id="null-literal">Null Literal</h3>
<p>The null pointer literal <code>null</code> has exactly the same semantics as in Java.</p>
<h3 id="type-literal">Type Literals</h3>
<p>The syntax for type literals is generally the plain name of the type, e.g. the snippet <code>String</code> is equivalent to the Java code <code>String.class</code>. Nested types use the delimiter <code>'.'</code>.</p>
<p>To disambiguate the expression, type literals may also be specified using the keyword <code>typeof</code>.</p>
<ul>
<li><code>Map.Entry</code> is equivalent to <code>Map.Entry.class</code></li>
<li><code>typeof(StringBuilder)</code> yields <code>StringBuilder.class</code></li>
</ul>
<p>Consequently it is possible to access the members of a type reflectively by using its plain name <code>String.getDeclaredFields</code>.</p>
<p>The keyword <code>typeof</code> is mandatory for references to array types, e.g. <code>typeof(int[]</code></p>
<p>Previous versions of Xtend (2.4.1 and before) used the dollar as the delimiter character for nested types and enforced the use of <code>typeof</code> for all type literals:</p>
<ul>
<li><code>typeof(Map$Entry)</code> yields <code>Map.Entry.class</code></li>
</ul>
<h3 id="collection-literals">Collection Literals</h3>
<p>The methods in <a href="https://github.com/eclipse/xtext-lib/blob/master/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/CollectionLiterals.java">CollectionLiterals</a> are automatically imported so it’s very easy and convenient to create instances of the various collection types the JDK offers.</p>
<pre><code class="language-xtend">val myList = newArrayList('Hello', 'World')
val myMap = newLinkedHashMap('a' -&gt; 1, 'b' -&gt; 2)
</code></pre>
<p>In addition xtend supports collection literals to create immutable collections and arrays, depending on the target type. An immutable list can be created like this:</p>
<pre><code class="language-xtend">val myList = #['Hello','World']
</code></pre>
<p>If the target type is an array as in the following example an array is created instead without any conversion:</p>
<pre><code class="language-xtend">val String[] myArray = #['Hello','World']
</code></pre>
<p>An immutable set can be created using curly braces instead of the squared brackets:</p>
<pre><code class="language-xtend">val mySet = #{'Hello','World'}
</code></pre>
<p>An immutable map is created like this:</p>
<pre><code class="language-xtend">val myMap = #{'a' -&gt; 1 ,'b' -&gt;2}
</code></pre>
<h3 id="arrays">Arrays</h3>
<p>Java arrays can be created either using a <a href="203_xtend_expressions.html#collection-literals">literal</a> as described in the previous section, or if it should be a new array with a fixed size, one of the methods from <a href="https://github.com/eclipse/xtext-lib/blob/master/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/ArrayLiterals.java">ArrayLiterals</a> can be used. The generic <code>newArrayOfSize(int)</code> method works for all reference types, while there is a specific factory method for each primitive type.</p>
<p>Example:</p>
<pre><code class="language-xtend">val String[] myArray = newArrayOfSize(400)
val int[] intArray = newIntArrayOfSize(400)
</code></pre>
<p>Retrieving and setting values of arrays is done through the extension methods <code>get(int)</code> and <code>set(int, T)</code> which are specifically overloaded for arrays and are translated directly to the equivalent native Java code <code>myArray[int]</code>.</p>
<p>Also <code>length</code> is available as an extension method and is directly translated to Java’s equivalent <code>myArray.length</code>.</p>
<p>Furthermore arrays are automatically converted to lists (<code>java.util.List</code>) when needed. This works similar to how boxing and unboxing between primitives and their respective wrapper types work.</p>
<p>Example:</p>
<pre><code class="language-xtend">val int[] myArray = #[1,2,3]
val List&lt;Integer&gt; myList = myArray
</code></pre>
<h2 id="type-casts">Type Casts</h2>
<p>A type cast behaves exactly like casts in Java, but has a slightly more readable syntax. Type casts bind stronger than any other operator but weaker than feature calls.</p>
<p>The conformance rules for casts are defined in the <a href="http://docs.oracle.com/javase/specs/jls/se6/html/conversions.html#5.5">Java Language Specification</a>. Here are some examples:</p>
<pre><code class="language-xtend">something as MyClass
42 as Integer
</code></pre>
<p>Instead of a plain type cast it’s also possible to use a <a href="203_xtend_expressions.html#switch-expression">switch with a type guard</a> which performs both the casting and the instance-of check. <a href="202_xtend_classes_members.html#polymorphic-dispatch">Dispatch methods</a> are another alternative to casts that offers the potential to enhance the number of expected and handled types in subclasses.</p>
<h2 id="operators">Infix Operators and Operator Overloading</h2>
<p>There are a couple of common predefined infix operators. These operators are not limited to operations on certain types. Instead an operator-to-method mapping allows to redefine the operators for any type just by implementing the corresponding method signature. As an example, the runtime library contains a class <a href="https://github.com/eclipse/xtext-lib/blob/master/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/BigDecimalExtensions.java">BigDecimalExtensions</a> that defines operators for <a href="http://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html">BigDecimals</a>. The following code is therefore perfectly valid:</p>
<pre><code class="language-xtend">val x = 2.71BD
val y = 3.14BD
val sum = x + y // calls BigDecimalExtension.operator_plus(x,y)
</code></pre>
<p>This is the complete list of all available operators and their corresponding method signatures:</p>
<table>
<tbody>
<tr>
<td><code>e1 += e2</code></td>
<td><code>e1.operator_add(e2)</code></td>
</tr>
<tr>
<td><code>e1 -= e2</code></td>
<td><code>e1.operator_remove(e2)</code></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><code>e1 || e2</code></td>
<td><code>e1.operator_or(e2)</code></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><code>e1 &amp;&amp; e2</code></td>
<td><code>e1.operator_and(e2)</code></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><code>e1 == e2</code></td>
<td><code>e1.operator_equals(e2)</code></td>
</tr>
<tr>
<td><code>e1 != e2</code></td>
<td><code>e1.operator_notEquals(e2)</code></td>
</tr>
<tr>
<td><code>e1 === e2</code></td>
<td><code>e1.operator_tripleEquals(e2)</code></td>
</tr>
<tr>
<td><code>e1 !== e2</code></td>
<td><code>e1.operator_tripleNotEquals(e2)</code></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><code>e1 &lt; e2</code></td>
<td><code>e1.operator_lessThan(e2)</code></td>
</tr>
<tr>
<td><code>e1 &gt; e2</code></td>
<td><code>e1.operator_greaterThan(e2)</code></td>
</tr>
<tr>
<td><code>e1 &lt;= e2</code></td>
<td><code>e1.operator_lessEqualsThan(e2)</code></td>
</tr>
<tr>
<td><code>e1 &gt;= e2</code></td>
<td><code>e1.operator_greaterEqualsThan(e2)</code></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><code>e1 -&gt; e2</code></td>
<td><code>e1.operator_mappedTo(e2)</code></td>
</tr>
<tr>
<td><code>e1 .. e2</code></td>
<td><code>e1.operator_upTo(e2)</code></td>
</tr>
<tr>
<td><code>e1 &gt;.. e2</code></td>
<td><code>e1.operator_greaterThanDoubleDot(e2)</code></td>
</tr>
<tr>
<td><code>e1 ..&lt; e2</code></td>
<td><code>e1.operator_doubleDotLessThan(e2)</code></td>
</tr>
<tr>
<td><code>e1 =&gt; e2</code></td>
<td><code>e1.operator_doubleArrow(e2)</code></td>
</tr>
<tr>
<td><code>e1 &lt;&lt; e2</code></td>
<td><code>e1.operator_doubleLessThan(e2)</code></td>
</tr>
<tr>
<td><code>e1 &gt;&gt; e2</code></td>
<td><code>e1.operator_doubleGreaterThan(e2)</code></td>
</tr>
<tr>
<td><code>e1 &lt;&lt;&lt; e2</code></td>
<td><code>e1.operator_tripleLessThan(e2)</code></td>
</tr>
<tr>
<td><code>e1 &gt;&gt;&gt; e2</code></td>
<td><code>e1.operator_tripleGreaterThan(e2)</code></td>
</tr>
<tr>
<td><code>e1 &lt;&gt; e2</code></td>
<td><code>e1.operator_diamond(e2)</code></td>
</tr>
<tr>
<td><code>e1 ?: e2</code></td>
<td><code>e1.operator_elvis(e2)</code></td>
</tr>
<tr>
<td><code>e1 &lt;=&gt; e2</code></td>
<td><code>e1.operator_spaceship(e2)</code></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><code>e1 + e2</code></td>
<td><code>e1.operator_plus(e2)</code></td>
</tr>
<tr>
<td><code>e1 - e2</code></td>
<td><code>e1.operator_minus(e2)</code></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><code>e1 * e2</code></td>
<td><code>e1.operator_multiply(e2)</code></td>
</tr>
<tr>
<td><code>e1 / e2</code></td>
<td><code>e1.operator_divide(e2)</code></td>
</tr>
<tr>
<td><code>e1 % e2</code></td>
<td><code>e1.operator_modulo(e2)</code></td>
</tr>
<tr>
<td><code>e1 ** e2</code></td>
<td><code>e1.operator_power(e2)</code></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><code>! e1</code></td>
<td><code>e1.operator_not()</code></td>
</tr>
<tr>
<td><code>- e1</code></td>
<td><code>e1.operator_minus()</code></td>
</tr>
<tr>
<td><code>+ e1</code></td>
<td><code>e1.operator_plus()</code></td>
</tr>
</tbody>
</table>
<p>The table above also defines the operator precedence in ascending order. The blank lines separate precedence levels. The assignment operators <code>+=</code> and <code>-=</code> are right-to-left associative in the same way as the plain assignment operator <code>=</code> is. That is a = b = c is executed as a = (b = c), all other operators are left-to-right associative. Parentheses can be used to adjust the default precedence and associativity.</p>
<h3 id="short-circuit-boolean-operators">Short-Circuit Boolean Operators</h3>
<p>If the operators <code>||</code>, <code>&amp;&amp;</code>, and <code>?:</code> are bound to the library methods <a href="https://github.com/eclipse/xtext-lib/blob/master/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/BooleanExtensions.java"><code>BooleanExtensions.operator_and(boolean l, boolean r)</code></a>, <a href="https://github.com/eclipse/xtext-lib/blob/master/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/BooleanExtensions.java"><code>BooleanExtensions.operator_or(boolean l, boolean r)</code></a> resp. <a href="https://github.com/eclipse/xtext-lib/blob/master/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/ObjectExtensions.java"><code>&lt;T&gt; T operator_elvis(T first, T second)</code></a> the operation is inlined and evaluated in short circuit mode. That means that the right hand operand might not be evaluated at all in the following cases:</p>
<ol>
<li>in the case of <code>||</code> the operand on the right hand side is not evaluated if the left operand evaluates to <code>true</code>.</li>
<li>in the case of <code>&amp;&amp;</code> the operand on the right hand side is not evaluated if the left operand evaluates to <code>false</code>.</li>
<li>in the case of <code>?:</code> the operand on the right hand side is not evaluated if the left operand evaluates to anything but <code>null</code>.</li>
</ol>
<p>Still you can overload these operators for your types or even override it for booleans, in which case both operands are always evaluated and the defined method is invoked, i.e. no short-circuit execution is happening.</p>
<h3 id="postfix-operators">Postfix Operators</h3>
<p>The two postfix operators <code>++</code> and <code>--</code> use the following method mapping:</p>
<table>
<tbody>
<tr>
<td><code>e1++</code></td>
<td><code>e1.operator_plusPlus()</code></td>
</tr>
<tr>
<td><code>e1--</code></td>
<td><code>e1.operator_minusMinus()</code></td>
</tr>
</tbody>
</table>
<h3 id="defined-operators-in-the-library">Defined Operators in The Library</h3>
<p>Xtend offers operators for common types from the JDK.</p>
<h4 id="equality-operators">Equality Operators</h4>
<p>In Xtend the equals operators (<code>==</code>,<code>!=</code>) are bound to <code>Object.equals</code>. So you can write:</p>
<pre><code class="language-xtend">if (name == 'Homer')
println('Hi Homer')
</code></pre>
<p>Java’s identity equals semantic is mapped to the tripple-equals operators <code>===</code> and <code>!==</code> in Xtend.</p>
<pre><code class="language-xtend">if (someObject === anotherObject)
println('same objects')
</code></pre>
<h4 id="comparison-operators">Comparison Operators</h4>
<p>In Xtend the usual comparison operators (<code>&gt;</code>,<code>&lt;</code>,<code>&gt;=</code>, and <code>&lt;=</code>) work as expected on the primitive numbers:</p>
<pre><code class="language-xtend">if (42 &gt; myNumber) {
...
}
</code></pre>
<p>In addition these operators are overloaded for all instances of <code>java.lang.Comparable</code>. So you can also write</p>
<pre><code class="language-xtend">if (startTime &lt; arrivalTime)
println("You are too late!")
</code></pre>
<h4 id="arithmetic-operators">Arithmetic Operators</h4>
<p>The arithmetic operators (<code>+</code>,<code>-</code>,<code>*</code>,<code>/</code>,<code>%</code>, and <code>**</code>) are not only available for the primitive types, but also for other reasonable types such as <code>BigDecimal</code> and <code>BigInteger</code>.</p>
<pre><code class="language-xtend">val x = 2.71BD
val y = 3.14BD
val sum = x + y // calls BigDecimalExtension.operator_plus(x,y)
</code></pre>
<h4 id="elvis-operator">Elvis Operator</h4>
<p>In addition to <a href="203_xtend_expressions.html#null-safe-feature-calls">null-safe feature calls</a> Xtend supports the elvis operator known from Groovy.</p>
<pre><code class="language-xtend">val salutation = person.firstName ?: 'Sir/Madam'
</code></pre>
<p>The right hand side of the expression is only evaluated if the left side was <code>null</code>.</p>
<h4 id="with-operator">With Operator</h4>
<p>The with operator is very handy when you want to initialize objects or when you want to use a particular instance a couple of time in subsequent lines of code. It simply passes the left hand side argument to the lambda on the right hand and returns the left hand after that.</p>
<p>Here’s an example:</p>
<pre><code class="language-xtend">val person = new Person =&gt; [
firstName = 'Homer'
lastName = 'Simpson'
address = new Address =&gt; [
street = '742 Evergreen Terrace'
city = 'SpringField'
]
]
</code></pre>
<h4 id="range-operators">Range Operators</h4>
<p>There are three different range operators. The most useful ones are <code>..&lt;</code> and <code>&gt;..</code> which create exclusive ranges.</p>
<pre><code class="language-xtend">// iterate the list forwards
for (i : 0 ..&lt; list.size) {
val element = list.get(i)
...
}
</code></pre>
<pre><code class="language-xtend">// or backwards
for (i : list.size &gt;.. 0) {
val element = list.get(i)
...
}
</code></pre>
<p>In addition there is the inclusive range, which is nice if you know both ends well. In the movies example the range is used to check whether a movie was made in a certain decade:</p>
<pre><code class="language-xtend">movies.filter[1980..1989.contains(year)]
</code></pre>
<p>Please keep in mind that there are other means to iterator lists, too. For example, you may want to use the <code>forEach</code> extension</p>
<pre><code class="language-xtend">list.forEach[ element, index |
.. // if you need access to the current index
]
list.reverseView.forEach[
.. // if you just need the element it in reverse order
]
</code></pre>
<h4 id="pair-operator">Pair Operator</h4>
<p>Sometimes you want to use a pair of two elements locally without introducing a new structure. In Xtend you can use the <code>-&gt;</code>-operator which returns an instance of <code>Pair&lt;A,B&gt;</code>:</p>
<pre><code class="language-xtend">val nameAndAge = 'Homer' -&gt; 42
</code></pre>
<p>If you want to surface a such a pair of values on the interface of a method or field, it’s generally a better idea to use a data class with a well defined name, instead:</p>
<pre><code class="language-xtend">@Data class NameAndAge {
String name
int age
}
</code></pre>
<h3 id="assignments">Assignments</h3>
<p><a href="203_xtend_expressions.html#variable-declaration">Local variables</a> can be assigned using the <code>=</code> operator.</p>
<pre><code class="language-xtend">var greeting = 'Hello'
if (isInformal)
greeting = 'Hi'
</code></pre>
<p>Of course, also non-final fields can be set using an assignment:</p>
<pre><code class="language-xtend">myObj.myField = 'foo'
</code></pre>
<h4 id="property-assignments">Setting Properties</h4>
<p>The lack of properties in Java leads to a lot of syntactic noise when working with data objects. As Xtend is designed to integrate with existing Java APIs it respects the Java Beans convention, hence you can call a setter using an assignment:</p>
<pre><code class="language-xtend">myObj.myProperty = 'foo' // calls myObj.setMyProperty("foo")
</code></pre>
<p>The setter is only used if the field is not accessible from the given context. That is why the <a href="204_activeannotations.html#property-annotation">@Property annotation</a> would rename the local field to <code>_myProperty</code>.</p>
<p>The return type of an assignment is the type of the right hand side, in case it is a simple assignment. If it is translated to a setter method it yields whatever the setter method returns.</p>
<h4 id="assignment-operators">Assignment Operators</h4>
<p>Compound assignment operators can be used as a shorthand for the assignment of a binary expression.</p>
<pre><code class="language-xtend">var BigDecimal bd = 45bd
bd += 12bd // equivalent to bd = bd + 12bd
bd -= 12bd // equivalent to bd = bd - 12bd
bd /= 12bd // equivalent to bd = bd / 12bd
bd *= 12bd // equivalent to bd = bd * 12bd
</code></pre>
<p>Compound assignments work automatically when the infix operator is declared. The following compound assignment operators are supported:</p>
<table>
<tbody>
<tr>
<td><code>e1 += e2</code></td>
<td><code>+</code></td>
</tr>
<tr>
<td><code>e1 -= e2</code></td>
<td><code>-</code></td>
</tr>
<tr>
<td><code>e1 *= e2</code></td>
<td><code>*</code></td>
</tr>
<tr>
<td><code>e1 /= e2</code></td>
<td><code>/</code></td>
</tr>
<tr>
<td><code>e1 %= e2</code></td>
<td><code>%</code></td>
</tr>
</tbody>
</table>
<hr />
<h2 id="blocks">Blocks</h2>
<p>The block expression allows to have imperative code sequences. It consists of a sequence of expressions. The value of the last expression in the block is the value of the complete block. The type of a block is also the type of the last expression. Empty blocks return <code>null</code> and have the type <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html">Object</a>. <a href="203_xtend_expressions.html#variable-declaration">Variable declarations</a> are only allowed within blocks and cannot be used as a block’s last expression.</p>
<p>A block expression is surrounded by curly braces. The expressions in a block can be terminated by an optional semicolon.</p>
<p>Here are two examples:</p>
<pre><code class="language-xtend">{
doSideEffect("foo")
result
}
</code></pre>
<pre><code class="language-xtend">{
var x = greeting;
if (x.equals("Hello ")) {
x + "World!"
} else {
x
}
}
</code></pre>
<h2 id="variable-declaration">Variable Declarations</h2>
<p>Variable declarations are only allowed within <a href="203_xtend_expressions.html#blocks">blocks</a>. They are visible from any subsequent expressions in the block.</p>
<p>A variable declaration starting with the keyword <code>val</code> denotes a value, which is essentially a final, unsettable variable. The variable needs to be declared with the keyword <code>var</code>, which stands for ‘variable’ if it should be allowed to reassign its value.</p>
<p>A typical example for using <code>var</code> is a counter in a loop:</p>
<pre><code class="language-xtend">{
val max = 100
var i = 0
while (i &lt; max) {
println("Hi there!")
i = i + 1
}
}
</code></pre>
<p>Shadowing variables from outer scopes is not allowed, the only exception is the <a href="203_xtend_expressions.html#implicit-variables">implicit variable</a><code>it</code>.</p>
<p>Variables declared outside of a lambda expression using the <code>var</code> keyword are not accessible from within the lambda expressions.</p>
<p>A local variable can be marked with the <code>extension</code> keyword to make its methods available as extensions (<a href="202_xtend_classes_members.html#extension-provider">see extension provider</a>).</p>
<h3 id="typing">Typing</h3>
<p>The type of the variable itself can either be explicitly declared or it can be inferred from the initializer expression. Here is an example for an explicitly declared type:</p>
<pre><code class="language-xtend">var List&lt;String&gt; strings = new ArrayList
</code></pre>
<p>In such cases, the type of the right hand expression must conform to the type of the expression on the left side.</p>
<p>Alternatively the type can be inferred from the initializater:</p>
<pre><code class="language-xtend">var strings = new ArrayList&lt;String&gt; // -&gt; msg is of type ArrayList&lt;String&gt;
</code></pre>
<h2 id="feature-calls">Field Access and Method Invocations</h2>
<p>A simple name can refer to a local field, variable or parameter. In addition it can point to a method with zero arguments, since empty parentheses are optional.</p>
<h3 id="property-access">Property Access</h3>
<p>If there is no field with the given name and also no method with the name and zero parameters accessible, a simple name binds to a corresponding Java-Bean getter method if available:</p>
<pre><code class="language-xtend">myObj.myProperty // myObj.getMyProperty() (.. in case myObj.myProperty is not visible.)
</code></pre>
<h3 id="implicit-variables">Implicit Variables this and it</h3>
<p>Like in Java the current instance of the class is bound to <code>this</code>. This allows for either qualified field access or method invocations like in:</p>
<pre><code class="language-xtend">this.myField
</code></pre>
<p>or it is possible to omit the receiver:</p>
<pre><code class="language-xtend">myField
</code></pre>
<p>You can use the variable name <code>it</code> to get the same behavior for any variable or parameter:</p>
<pre><code class="language-xtend">val it = new Person
name = 'Horst' // translates to 'it.setName("Horst");'
</code></pre>
<p>Another speciality of the variable <code>it</code> is that it is allowed to be shadowed. This is especially useful when used together with <a href="203_xtend_expressions.html#lambdas">lambda expressions</a>.</p>
<p>As <code>this</code> is bound to the surrounding object in Java, <code>it</code> can be used in finer-grained constructs such as <a href="203_xtend_expressions.html#lambdas">lambda expressions</a>. That is why <code>it.myProperty</code> has higher precedence than <code>this.myProperty</code>.</p>
<h3 id="static-access">Static Access</h3>
<p>For accessing a static field or method you can use the recommended Java syntax or the more explicit double colon <code>::</code>. That means, the following epxressions are pairwise equivalent:</p>
<pre><code class="language-xtend">MyClass.myField
MyClass::myField
</code></pre>
<pre><code class="language-xtend">com.acme.MyClass.myMethod('foo')
com.acme.MyClass::myMethod('foo')
com::acme::MyClass::myMethod('foo')
</code></pre>
<p>Alternatively you could import the method or field using a <a href="202_xtend_classes_members.html#imports">static import</a>.</p>
<h3 id="null-safe-feature-calls">Null-Safe Feature Calls</h3>
<p>Checking for <code>null</code> references can make code very unreadable. In many situations it is ok for an expression to return <code>null</code> if a receiver was <code>null</code>. Xtend supports the safe navigation operator <code>?.</code> to make such code better readable.</p>
<p>Instead of writing</p>
<pre><code class="language-java">if (myRef != null) myRef.doStuff()
</code></pre>
<p>one can write</p>
<pre><code class="language-xtend">myRef?.doStuff
</code></pre>
<p>Arguments that would be passed to the method are only evaluated if the method will be invoked at all.</p>
<p>For primitive types the default value is returned (e.g. 0 for int). This may not be what you want in some cases, so a warning will be raised by default. You can turn that off in the preferences if you wish.</p>
<h2 id="constructor-call">Constructor Calls</h2>
<p>Constructor calls have the same syntax as in Java. The only difference is that empty parentheses are optional:</p>
<pre><code class="language-xtend">new String() == new String
new ArrayList&lt;BigDecimal&gt;() == new ArrayList&lt;BigDecimal&gt;
</code></pre>
<p>If type arguments are omitted, they will be inferred from the current context similar to Java’s diamond operator on generic method and constructor calls.</p>
<h2 id="lambdas">Lambda Expressions</h2>
<p>A lambda expression is basically a piece of code wrapped into an object to pass it around. As a Java developer it is best to think of a lambda expression as an anonymous class with a single method, i.e. like in the following Java code :</p>
<pre><code class="language-java">// Java Code!
final JTextField textField = new JTextField();
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textField.setText("Something happened!");
}
});
</code></pre>
<p>This kind of anonymous classes can be found everywhere in Java code and have always been the poor-man’s replacement for lambda expressions in Java. This has been improved with <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html">Java 8 lambda expressions</a>, which are conceptually very similar to Xtend lambda expressions. Depending on the selected target language version, Xtend lambdas are translated differently to Java: Java lambdas are generated for Java 8 (since 2.8), while anonymous classes are generated for lower versions.</p>
<p>The code above can be written in Xtend like this:</p>
<pre><code class="language-xtend">val textField = new JTextField
textField.addActionListener([ ActionEvent e |
textField.text = "Something happened!"
])
</code></pre>
<p>As you might have guessed, a lambda expression is surrounded by square brackets (inspired from Smalltalk). Similarly to a method, a lambda expression may declare parameters. The lambda above has one parameter called <code>e</code> which is of type <code>ActionEvent</code>. You do not have to specify the type explicitly because it can be inferred from the context:</p>
<pre><code class="language-xtend">textField.addActionListener([ e |
textField.text = "The command '" + e.actionCommand + "' happened!"
])
</code></pre>
<p>You do not need to specify the argument names. If you leave them out, a single argument is named <code>it</code>. If the lambda has more arguments, the implicit names are <code>$1,$2,...,$n</code> depending on the number of arguments of course. Here’s an example with a single argument named <code>it</code>. In this case <code>actionCommand</code> is equivalent to <code>it.actionCommand</code>.</p>
<pre><code class="language-xtend">textField.addActionListener([
textField.text = "The command '" + actionCommand + "' happened!"
])
</code></pre>
<p>A lambda expression with zero arguments can be written with or without the bar. They are both the same.</p>
<pre><code class="language-xtend">val Runnable aBar = [|
println("Hello I'm executed!")
]
val Runnable noBar = [
println("Hello I'm executed!")
]
</code></pre>
<p>When a method call’s last parameter is a lambda it can be passed right after the parameter list. For instance if you want to sort some strings by their length, you could write :</p>
<pre><code class="language-xtend">Collections.sort(someStrings) [ a, b |
a.length - b.length
]
</code></pre>
<p>which is just the same as writing</p>
<pre><code class="language-xtend">Collections.sort(someStrings, [ a, b |
a.length - b.length
])
</code></pre>
<p>Since you can leave out empty parentheses for methods which get a lambda as their only argument, you can reduce the code above further down to:</p>
<pre><code class="language-xtend">textField.addActionListener [
textField.text = "Something happened!"
]
</code></pre>
<p>A lambda expression also captures the current scope. Any final local variables and all parameters that are visible at construction time can be referred to from within the lambda body. That is exactly what we did with the variable <code>textField</code> above.</p>
<p>The variable <code>this</code> refers to the outer class. The lambda instance itself is available with the identifier <code>self</code>.</p>
<pre><code class="language-xtend">val lineReader = new LineReader(r);
val AbstractIterator&lt;String&gt; lineIterator = [|
val result = lineReader.readLine
if (result==null)
self.endOfData
return result
]
</code></pre>
<h3 id="closure-types">Typing</h3>
<p>Lambdas are expressions which produce <em>Function</em> objects. The type of a lambda expression generally depends on the target type, as seen in the previous examples. That is, the lambda expression can coerce to any interface or abstract class which has declared only one abstract method. This allows for using lambda expressions in many existing Java APIs in a similar way as <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#target-typing">Java 8 lambdas</a> can be used.</p>
<p>However, if you write a lambda expression without having any target type expectation, like in the following assignment:</p>
<pre><code class="language-xtend">val toUpperCaseFunction = [ String s | s.toUpperCase ] // inferred type is (String)=&gt;String
</code></pre>
<p>The type will be one of the inner types found in <a href="https://github.com/eclipse/xtext-lib/blob/master/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/Functions.java">Functions</a> or <a href="https://github.com/eclipse/xtext-lib/blob/master/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/Procedures.java">Procedures</a>. It is a procedure if the return type is <code>void</code>, otherwise it is a function.</p>
<p>Xtend supports a shorthand syntax for function types. Instead of writing <code>Function1&lt;? super String,? extends String&gt;</code> which is what you will find in the generated Java code, you can simply write <code>(String)=&gt;String</code>.</p>
<p>Example:</p>
<pre><code class="language-xtend">val (String)=&gt;String stringToStringFunction = [ toUpperCase ]
// or
val Function1&lt;? super String,? extends String&gt; same = [ toUpperCase ]
// or
val stringToStringFunction2 = [ String s | s.toUpperCase ] // inferred type is (String)=&gt;String
</code></pre>
<p>Checked exceptions that are thrown in the body of a lambda expression but not declared in the implemented method of the target type are thrown using the <a href="202_xtend_classes_members.html#declared-exceptions">sneaky-throw technique</a>. Of course you can always <a href="203_xtend_expressions.html#xtend-expressions-try-catch">catch and handle</a> them.</p>
<h2 id="anonymous-classes">Anonymous Classes</h2>
<p>An anonymous class in Xtend has the very same semantics as in Java (see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5">Java Language Specification</a>). Here’s an example:</p>
<pre><code class="language-xtend">val tabListener = new ActionBar.TabListener() {
override onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// show the given tab
}
override onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// hide the given tab
}
override onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// probably ignore this event
}
};
</code></pre>
<h2 id="if-expression">If Expression</h2>
<p>An if-expression is used to choose between two different values based on a predicate.</p>
<p>An expression</p>
<pre><code class="language-xtend">if (p) e1 else e2
</code></pre>
<p>results in either the value <code>e1</code> or <code>e2</code> depending on whether the predicate <code>p</code> evaluates to <code>true</code> or <code>false</code>. The else part is optional which is a shorthand for an else branch that returns the default value of the current type, e.g. for reference type this is equivalent to <code>else null</code>. That means</p>
<pre><code class="language-xtend">if (foo) x
</code></pre>
<p>is a short hand for</p>
<pre><code class="language-xtend">if (foo) x else null
</code></pre>
<p>The type of an if expression is the common super type of the return types <code>T1</code> and <code>T2</code> of the two expression <code>e1</code> and <code>e2</code>.</p>
<p>While the if expression has the syntax of Java’s if statement it behaves more like Java’s ternary operator (<code>predicate ? thenPart : elsePart</code>), because it is an expression and returns a value. Consequently, you can use if expressions deeply nested within expressions:</p>
<pre><code class="language-xtend"> val name = if (firstName != null) firstName + ' ' + lastName else lastName
</code></pre>
<h2 id="switch-expression">Switch Expression</h2>
<p>The switch expression is very different from Java’s switch statement. The use of <code>switch</code> is not limited to certain values but can be used for any object reference. <code>Object.equals(Object)</code> is used to compare the value in the case with the one you are switching over. Given the following example:</p>
<pre><code class="language-xtend">switch myString {
case myString.length &gt; 5 : "a long string."
case 'some' : "It's some string."
default : "It's another short string."
}
</code></pre>
<p>the main expression <code>myString</code> is evaluated first and then compared to each case sequentially. If the case expression is of type <code>boolean</code>, the case matches if the expression evaluates to <code>true</code>. If it is not of type <code>boolean</code> it is compared to the value of the main expression using <code>Object.equals(Object)</code>.</p>
<p>If a case is a match, that is it evaluates to <code>true</code> or the result equals the one we are switching over, the case expression after the colon is evaluated and is the result of the whole switch expression.</p>
<p>The main expression can also be a computed value instead of a field or variable. If you want to reuse that value in the body of the switch expression, you can create a local value for that by using the following notation which is similar to the syntax in <a href="203_xtend_expressions.html#for-loop"><code>for</code> loops</a>.</p>
<pre><code class="language-xtend">switch myString : someComputation() {
..
}
</code></pre>
<h3 id="type-guards">Type guards</h3>
<p>Instead of or in addition to the case guard you can specify a <em>type guard</em>. The case only matches if the switch value conforms to this type. A case with both a type guard and a predicate only matches if both conditions match. If the switch value is a field, parameter or variable, it is automatically casted to the given type within the predicate and the case body.</p>
<pre><code class="language-xtend">def length (Object x) {
switch x {
String case x.length &gt; 0 : x.length // length is defined for String
List&lt;?&gt; : x.size // size is defined for List
default : -1
}
}
</code></pre>
<p>Handling multiple types in one case statement can be realized with a <em>multi-type guard</em> expression. By specifying an arbitrary number of types separated by a <code>|</code> multiple types can be processed by a single case statement. Within the case block, the intersection type is available for further processing.</p>
<pre><code class="language-xtend">def length (Object x) {
switch x {
List&lt;?&gt; | Set&lt;?&gt; : x.size // size is defined for intersection type Collection
String case x.length &gt; 0: x.length // length is defined for String
default: -1
}
}
</code></pre>
<p>Switches with type guards are a safe and much more readable alternative to instance of / casting cascades you might know from Java.</p>
<h3 id="fall-through">Fall Through</h3>
<p>You can have multiple type guards and cases separated with a comma, to have all of them share the same then part.</p>
<pre><code class="language-xtend">def isMale(String salutation) {
switch salutation {
case "Mr.",
case "Sir" : true
default : false
}
}
</code></pre>
<h2 id="ternary-expression">Ternary Expression</h2>
<p>Additionally to the <a href="203_xtend_expressions.html#if-expression">if expression</a> you can use the ternary operator as you are used to from Java.</p>
<pre><code class="language-xtend">val x = flag?"Hello":"Goodbye"
</code></pre>
<h2 id="for-loop">For Loop</h2>
<p>The for loop</p>
<pre><code class="language-xtend">for (T1 variable : arrayOrIterable) expression
</code></pre>
<p>is used to execute a certain expression for each element of an array or an instance of <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html">Iterable</a>. The local <code>variable</code> is final, hence cannot be updated.</p>
<p>The type of a for loop is <code>void</code>. The type of the local variable can be inferred from the iterable or array that is processed.</p>
<pre><code class="language-xtend">for (String s : myStrings) {
doSideEffect(s)
}
for (s : myStrings)
doSideEffect(s)
</code></pre>
<h2 id="traditional-for-loop">Basic For Loop</h2>
<p>The traditional for loop</p>
<pre><code class="language-xtend">for (&lt;init-expression&gt; ; &lt;predicate&gt; ; &lt;update-expression&gt;) body-expression
</code></pre>
<p>is very similar to the one known from Java, or even C. When executed, it first executes the <code>init-expression</code>, where local variables can be declared. Next the <code>predicate</code> is executed and if it evaluates to <code>true</code>, the <code>body-expression</code> is executed. On any subsequent iterations the <code>update-expressio</code> is executed instead of the init-expression. This happens until the <code>predicate</code> returns <code>false</code>.</p>
<p>The type of a for loop is <code>void</code>.</p>
<pre><code class="language-xtend">for (var i = 0 ; i &lt; s.length ; i++) {
println(s.subString(0,i)
}
</code></pre>
<h2 id="while-expression">While Loop</h2>
<p>A while loop</p>
<pre><code class="language-xtend">while (predicate) expression
</code></pre>
<p>is used to execute a certain expression unless the predicate is evaluated to <code>false</code>. The type of a while loop is <code>void</code>.</p>
<pre><code class="language-xtend">while (true) {
doSideEffect("foo")
}
while ((i=i+1) &lt; max)
doSideEffect("foo")
</code></pre>
<h2 id="do-while-expression">Do-While Loop</h2>
<p>A do-while loop</p>
<pre><code class="language-xtend">do expression while (predicate)
</code></pre>
<p>is used to execute a certain expression until the predicate is evaluated to <code>false</code>. The difference to the <a href="203_xtend_expressions.html#while-expression">while loop</a> is that the execution starts by executing the block once before evaluating the predicate for the first time. The type of a do-while loop is <code>void</code>.</p>
<pre><code class="language-xtend">do {
doSideEffect("foo");
} while (true)
do doSideEffect("foo") while ((i=i+1)&lt;max)
</code></pre>
<h2 id="xtend-expressions-return">Return Expression</h2>
<p>A method or lambda expression automatically returns the value of its body expression. If it is a <a href="203_xtend_expressions.html#blocks">block expression</a> this is the value of the last expression in it. However, sometimes you want to return early or make it explicit.</p>
<p>The syntax is just like in Java:</p>
<pre><code class="language-xtend">listOfStrings.map [ e |
if (e==null)
return "NULL"
e.toUpperCase
]
</code></pre>
<h2 id="xtend-expressions-throw">Throwing Exceptions</h2>
<p>Throwing <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html">Throwable</a>s up the call stack has the same semantics and syntax as in Java.</p>
<pre><code class="language-xtend">{
...
if (myList.isEmpty)
throw new IllegalArgumentException("the list must not be empty")
...
}
</code></pre>
<h2 id="xtend-expressions-try-catch">Try, Catch, Finally</h2>
<p>The try-catch-finally expression is used to handle exceptional situations. Checked exceptions are treated like runtime exceptions and only optionally validated. You can but do not have to catch them as they will be silently thrown (see the <a href="202_xtend_classes_members.html#declared-exceptions">section on declared exceptions</a>).</p>
<pre><code class="language-xtend">try {
throw new RuntimeException()
} catch (NullPointerException e) {
// handle e
} finally {
// do stuff
}
</code></pre>
<p>For try-catch it is again beneficial that it is an expression, because you can write code like the following and do not have to rely on non-final variables:</p>
<pre><code class="language-xtend">val name = try {
readFromFile
} catch (IOException e) {
"unknown"
}
</code></pre>
<p>Handling multiple exceptions in a single catch block can be realized using a <em>multi-catch clause</em>. The <em>multi-catch clause</em> can handle an arbitrary number of exceptions separated by <code>|</code>. Within the catch block, the intersection exception type of the exceptions caught by the <em>multi-catch clause</em> is available for further processing. If handling one exception covers another exception handled in the <em>multi-catch clause</em> an error is raised.</p>
<pre><code class="language-xtend">def readFile (String path) {
try {
readFromPath (path)
} catch (FileNotFoundException | StreamCorruptedException it) {
logException
}
}
</code></pre>
<h2 id="xtend-expressions-try-with-resources">Try With Resources</h2>
<p>Like in Java you can use the try-with-resources expression to automatically close resources.</p>
<pre><code class="language-xtend"> try (val resource = new StringReader("This \n is a text!"))
return resource.read
</code></pre>
<h2 id="xtend-expressions-synchronized">Synchronized</h2>
<p>The synchonized expression does the same as it does in Java (see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.19">Java Language Specification</a>). The only difference is that in Xtend it is an expression and can therefore be used at more places.</p>
<pre><code class="language-xtend">synchronized(lock) {
println("Hello")
}
</code></pre>
<pre><code class="language-xtend">val name = synchronized(lock) {
doStuff()
}
</code></pre>
<h2 id="templates">Template Expressions</h2>
<p>Templates allow for readable string concatenation. Templates are surrounded by triple single quotes (<code>'''</code>). A template expression can span multiple lines and expressions can be nested which are evaluated and their <code>toString()</code> representation is automatically inserted at that position.</p>
<p>The terminals for interpolated expression are so called guillemets <code>«expression»</code>. They read nicely and are not often used in text so you seldom need to escape them. These escaping conflicts are the reason why template languages often use longer character sequences like e.g. <code>&lt;%= expression %&gt;</code> in JSP, for the price of worse readability. The downside with the guillemets in Xtend is that you will have to have a consistent encoding. Always use UTF-8 and you are good.</p>
<p>If you use the Eclipse plug-in the guillemets will be inserted on content assist within a template. They are additionally bound to <kbd>CTRL</kbd> + <kbd>&lt;</kbd> and <kbd>CTRL</kbd> + <kbd>&gt;</kbd> for <code>«</code> and <code>»</code> respectively.</p>
<p>Let us have a look at an example of how a typical method with a template expressions looks like:</p>
<pre><code class="language-xtend">def someHTML(String content) '''
&lt;html&gt;
&lt;body&gt;
«content»
&lt;/body&gt;
&lt;/html&gt;
'''
</code></pre>
<p>As you can see, template expressions can be used as the body of a method. If an interpolation expression evaluates to <code>null</code> an empty string is added.</p>
<p>Template expressions can occur everywhere. Here is an example showing it in conjunction with the powerful <a href="203_xtend_expressions.html#switch-expression">switch expression</a>:</p>
<pre><code class="language-xtend">def toText(Node n) {
switch n {
Contents : n.text
A : '''&lt;a href="«n.href»"&gt;«n.applyContents»&lt;/a&gt;'''
default : '''
&lt;«n.tagName»&gt;
«n.applyContents»
&lt;/«n.tagName»&gt;
'''
}
}
</code></pre>
<h3 id="template-comment">Comments in Templates</h3>
<p>Normal single line comments <code>//...</code> and multiline comments <code>/* ... */</code> will not work inside a template expression. However, you can comment out a complete line inside a template expression using <code>««« .....</code>.</p>
<pre><code class="language-xtend">def someHTML(String body) '''
&lt;html&gt;
&lt;body&gt;
««« this will not be visible in the result
««« nor will this: «body»
&lt;/body&gt;
&lt;/html&gt;
'''
</code></pre>
<p>For convenience you can use the normal toggle comment commands from context menu or via shortcuts</p>
<ul>
<li>On PC
<ul>
<li><kbd>CTRL</kbd> + <kbd>7</kbd></li>
<li><kbd>CTRL</kbd> + <kbd>/</kbd></li>
<li><kbd>CTRL</kbd> + <kbd></kbd> + <kbd>C</kbd></li>
</ul>
</li>
<li>On Mac
<ul>
<li><kbd></kbd> + <kbd>7</kbd></li>
<li><kbd></kbd> + <kbd>/</kbd></li>
<li><kbd></kbd> + <kbd></kbd> + <kbd>C</kbd></li>
</ul>
</li>
</ul>
<h3 id="template-if">Conditions in Templates</h3>
<p>There is a special <code>IF</code> to be used within templates:</p>
<pre><code class="language-xtend">def someHTML(Paragraph p) '''
&lt;html&gt;
&lt;body&gt;
«IF p.headLine != null»
&lt;h1&gt;«p.headline»&lt;/h1&gt;
«ENDIF»
&lt;p&gt;
«p.text»
&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
'''
</code></pre>
<p>You can also use <code>IF...ELSE...ENDIF</code> or <code>IF...ELSEIF...ENDIF</code> expressions:</p>
<pre><code class="language-xtend">def someHTML(Paragraph p) '''
&lt;html&gt;
&lt;body&gt;
«IF p.headLine != null»
&lt;h1&gt;«p.headline»&lt;/h1&gt;
«ELSE»
&lt;h1&gt;«p.standartHeadline»&lt;/h1&gt;
«ENDIF»
&lt;p&gt;
«p.text»
&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
'''
</code></pre>
<h3 id="template-foreach">Loops in Templates</h3>
<p>Also a <code>FOR</code> expression is available:</p>
<pre><code class="language-xtend">def someHTML(List&lt;Paragraph&gt; paragraphs) '''
&lt;html&gt;
&lt;body&gt;
«FOR p : paragraphs»
«IF p.headLine != null»
&lt;h1&gt;«p.headline»&lt;/h1&gt;
«ENDIF»
&lt;p&gt;
«p.text»
&lt;/p&gt;
«ENDFOR»
&lt;/body&gt;
&lt;/html&gt;
'''
</code></pre>
<p>The for expression optionally allows to specify what to prepend (<code>BEFORE</code>), put in-between (<code>SEPARATOR</code>), and what to put at the end (<code>AFTER</code>) of all iterations. <code>BEFORE</code> and <code>AFTER</code> are only executed if there is at least one iteration. (<code>SEPARATOR</code>) is only added between iterations. It is executed if there are at least two iterations.</p>
<p>Here is an example:</p>
<pre><code class="language-xtend">def someHTML(List&lt;Paragraph&gt; paragraphs) '''
&lt;html&gt;
&lt;body&gt;
«FOR p : paragraphs BEFORE '&lt;div&gt;' SEPARATOR '&lt;/div&gt;&lt;div&gt;' AFTER '&lt;/div&gt;'»
«IF p.headLine != null»
&lt;h1&gt;«p.headline»&lt;/h1&gt;
«ENDIF»
&lt;p&gt;
«p.text»
&lt;/p&gt;
«ENDFOR»
&lt;/body&gt;
&lt;/html&gt;
'''
</code></pre>
<h3 id="template-type">Typing</h3>
<p>The template expression is of type <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html">CharSequence</a>. It is automatically converted to <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html">String</a> if that is the expected target type.</p>
<h3 id="whitespace-handling">White Space Handling</h3>
<p>One of the key features of templates is the smart handling of white space in the template output. The white space is not written into the output data structure as is but preprocessed. This allows for readable templates as well as nicely formatted output. The following three rules are applied when the template is evaluated:</p>
<ol>
<li>Indentation in the template that is relative to a control structure will not be propagated to the output string. A control structure is a <code>FOR</code>-loop or a condition (<code>IF</code>) as well as the opening and closing marks of the template string itself. The indentation is considered to be relative to such a control structure if the previous line ends with a control structure followed by optional white space. The amount of indentation white space is not taken into account but the delta to the other lines.</li>
<li>Lines that do not contain any static text which is not white space but do contain control structures or invocations of other templates which evaluate to an empty string, will not appear in the output.</li>
<li>Any newlines in appended strings (no matter they are created with template expressions or not) will be prepended with the current indentation when inserted.</li>
</ol>
<p>Although this algorithm sounds a bit complicated at first it behaves very intuitively. In addition the syntax coloring in Eclipse communicates this behavior.</p>
<p><img src="images/Xtend_template_coloring.png" alt="Syntax Coloring For Templates In Eclipse" /></p>
<p>The behavior is best described with a set of examples. The following table assumes a data structure of nested nodes.</p>
<table>
<tbody>
<tr>
</tr>
</tbody>
</table>
<pre><code class="language-xtend">class Template {
def print(Node n) '''
node «n.name» {}
'''
}
</code></pre>
<table>
<tbody>
<tr>
</tr>
</tbody>
</table>
<pre><code>node NodeName {}
</code></pre>
<table>
<tbody>
<tr>
</tr>
</tbody>
</table>
<p>The indentation before <code>node «n.name»</code> will be skipped as it is relative to the opening mark of the template string and thereby not considered to be relevant for the output but only for the readability of the template itself.</p>
<table>
<tbody>
<tr>
</tr>
</tbody>
</table>
<pre><code class="language-xtend">class Template {
def print(Node n) '''
node «n.name» {
«IF hasChildren»
«n.children.map[print]»
«ENDIF»
}
'''
}
</code></pre>
<table>
<tbody>
<tr>
</tr>
</tbody>
</table>
<pre><code>node Parent{
node FirstChild {
}
node SecondChild {
node Leaf {
}
}
}
</code></pre>
<table>
<tbody>
<tr>
</tr>
</tbody>
</table>
<p>As in the previous example, there is no indentation on the root level for the same reason. The first nesting level has only one indentation level in the output. This is derived from the indentation of the <code>IF hasChildren</code> condition in the template which is nested in the node. The additional nesting of the recursive invocation <code>children.map[print]</code> is not visible in the output as it is relative the surrounding control structure. The line with <code>IF</code> and <code>ENDIF</code> contain only control structures thus they are skipped in the output. Note the additional indentation of the node <em>Leaf</em> which happens due to the first rule: Indentation is propagated to called templates.</p>
<hr />
<p><strong><a href="204_activeannotations.html">Next Chapter: Active Annotations</a></strong></p>
</div>
</div>
</div>
</div>
</div>
</div>
<footer class="site-footer">
<div id="extra">
<div class="container inner-footer">
<div class="row">
<div class="span6">
<h3 class="footer-links-header">Quick Links</h3>
<ul class="footer-links clearfix">
<li><a href="http://www.eclipse.org/legal/privacy.php">Privacy Policy</a></li>
<li><a href="http://www.eclipse.org/legal/termsofuse.php">Terms of Use</a></li>
<li><a href="http://www.eclipse.org/legal/copyright.php">Copyright Agent</a></li>
<li><a href="http://www.eclipse.org/legal/">Legal</a></li>
</ul>
<ul class="footer-links clearfix">
<li><a href="http://www.eclipse.org">Eclipse Home</a></li>
<li><a href="http://marketplace.eclipse.org/">Market Place</a></li>
<li><a href="http://www.planeteclipse.org/">Eclipse Planet</a></li>
<li><a href="https://www.eclipse.org/forums/index.php/f/27/">Xtext Forum</a></li>
</ul>
</div>
<div class="span6">
<!-- Social Media Links -->
<h3 class="footer-links-header"">Social Media</h3>
<ul class="footer-links clearfix">
<li>
<a href="https://twitter.com/xtendlang"><img src="/xtend/images/Twitter-bird-darkgray.png" class="img-responsive" style="margin-right: 5px;height: 1em;" alt="Twitter icon">@xtendlang on Twitter</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<a href="#" class="scrollup fadeOutRight animated" style="display: none;">ScrollUp</a>
<a href="http://dryicons.com/">Icons by http://dryicons.com</a>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/xtend/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="/xtend/js/bootstrap.min.js" type="text/javascript"></script>
<!-- include pretty-print files -->
<script src="/xtend/js/prettify.js" type="text/javascript" ></script>
<script src="/xtend/js/lang-xtend.js" type="text/javascript"></script>
<!-- Include the plug-in -->
<script src="/xtend/js/jquery.prettyPhoto.js" type="text/javascript"></script>
<script src="/xtend/js/jquery.easing.1.3.js" type="text/javascript"></script>
<script src="/xtend/js/custom.js" type="text/javascript"></script>
<!--script src="https://apis.google.com/js/platform.js" async defer></script-->
<!--script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push([ '_setAccount', 'UA-2429174-4' ]);
_gaq.push([ '_trackPageview' ]);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl'
: 'http://www')
+ '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script-->
</footer>
</body>
</html>