Conditional Expressions

To express choosing between two alternatives, Scala has a conditional expression if-else. It looks like a if-else in Java, but is used for expressions, not statements.
Example:
def abs(x: Int) = if (x >= 0) x else -x
x >= 0 is a predicate, of type Boolean.
Here are reduction rules for conditional expressions (e1 and e2 are arbitrary expressions, b is boolean expression)
if (b) e1 else e2:
if (true) e1 else e2   --> e1
if (false) e1 else e2  --> e2

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Scala snippets
Cosmo
Sign Up Now
or Subscribe for future quizzes