if
expressions in Scala are a control structure. The syntax of the if
expression is as follows:
if (expression) {
doSomething()
}
In the syntax above, expression
represents any Scala expression that returns a boolean value (either true
or false
). The code inside the curly braces gets executed only if the expression
returns true
.
Scala also supports else if
and else
constructs like other programming languages:
if (expression1) {
doSomething1()
} else if (expression2) {
doSomething2()
} else {
doSomething3()
}
if
expressionIn Scala, the if
expression always returns a value. This allows the if
construct to be used as an expression itself. Consider the following example:
object Main extends App {var x = if (0 == 0) "Zero" else "One"println(x)}
In the example above, the value of x
is returned by the if
expression. The if
expression compares 0 == 0
and returns the string Zero
(since 0 == 0
is true
). This string gets stored in the variable x
and is printed on the standard output.
Free Resources