Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are if expressions in Scala?

Hammad Nasir

Overiew

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()
}

In-line if expression

In 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.

RELATED TAGS

scala

CONTRIBUTOR

Hammad Nasir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring