Tech and Media Labs
This site uses cookies to improve the user experience.




Scala if

Jakob Jenkov
Last update: 2014-05-25

The Scala if command executes a certain block of code, if a certain condition is true. Here is an example:

var myInt : Int = 0;

if(myInt == 0) {
  println("myInt == 0");
}

This example would print the text "myInt == 0" to the console.

The expression inside the paranthesis must result in a boolean value (true or false). For instance, if you call a method inside the paranthesis, that method must return a boolean value.

if - else

You can add an else to an if condition, like this:

var myInt : Int = 1;

if(myInt == 0) {
    println("myInt == 0");
} else {
    println("myInt != 0");
}

Omitting { } in if - statements

Like in Java it is possible to omit the {} in an if-statement around the code to execute, if the code consists of a single line. Here is an example:

var myInt : Int = 1;

if(myInt == 0)
    println("myInt == 0");
 else
    println("myInt != 0");

if - statements as Functions

In Scala if-statements can be used as functions. That is, they can return a value. Here is an example:

var myInt : Int = 1;

var myText : String =
   if(myInt == 0) "myInt == 0";
   else           "myInt != 0";

println(myText);

Notice how the myText variable is assigned to the result of the if-statement.

The if-statement returns the last value assigned inside it. Thus, in this case, since else-clause is executed, the last value assigned is the "myInt !=0". If the if or else clause had more than one statement in them, remember that only the last assignment would be returned.

Since if-statements behave like functions, you can use them in any place you could normally use a function.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC