Fork me on GitHub

If-Then-Else Expressions

An if-expression is used to choose between two different values based on a predicate.

##1. Standard If-Then-Else Syntax

The following results in either the value e1 or e2 depending on whether the predicate e1 !== null evaluates to true or false.

if (e1 !== null) 

##2. Optional Else Part

The else part is optional, which is a shorthand for an else branch that returns the default value of the current type.

if (e1 !== null) e1

##3. Conditional Operator

Sometimes, it is useful to put a if-then-else expression inside another expression. This syntax is known as the conditional operator, inline if, or ternary if in many programming languages. In programming languages such as Java or C/C++, this conditional operator has the syntax:

a ? b : c

It evaluates to b if the value of a is true, otherwise to c.

In SARL, this specific syntax is not supported. The standard if-then-else expression (explained above) is an expression. It means that it could be included into another expression like all the other expressions. Consequently, there is no need of a specific syntax for the conditional operator in SARL. The following example is the SARL equivelant of the Java conditional operator:

if (a) b else c

You can use if expressions deeply nested within expressions:

val name = if (e1 !== null) e1 + ' ' + e2 else e2

##4. Acknowledgements

This documentation is inspired by the documentations from the Xtext and Xtend projects.

##5. Legal Notice

Copyright © 2014-2019 the original authors or authors.

Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License.

You are free to reproduce the content of this page on copyleft websites such as Wikipedia.

Generated with the translator 0.10.0.