Decide with if
In this lesson, we will go over how to use the `if` expression.
We'll cover the following
Introduction
The if
expression is a conditional statement. It allows you to incorporate conditions in your code which need to be fulfilled before the code can execute.
Conditional statements are incredibly powerful as they take the state of the program into consideration and act accordingly. This results in smarter compilation as the compiler is now provided with a decision-making capability.
Control Flow
Let’s look at the control flow of if
.
The above flow is showing that if the condition has been fulfilled, the compiler will execute the conditional code and if the condition has not been fulfilled, the compiler will exit that block of code without executing the conditional code.
Syntax
Before we see the if
expression in action, let’s go over the syntax and see how to write a block of code with if
using Scala.
The syntax is pretty straight forward with an if
followed by the condition to be checked in ()
which is further followed by the code to be executed if the condition is true
.
To make the code more readable, you can write the conditional code underneath the if
expression and condition. In this case, surround the conditional code in curly brackets ({}
).
The condition must be an expression of type
Boolean
. If the condition istrue
, the code will execute. If the condition isfalse
, the compiler will exit the code.
if
in Action
In the example below, we want to change the first element of an array, but before we can do that we need to make sure the array is not empty.
var arrayOfEmotions = Array("happy","sad","angry","excited")if (!arrayOfEmotions.isEmpty) {arrayOfEmotions(0) = "joyful"}// Driver CodearrayOfEmotions.foreach(println)
In the code above, the condition !arrayOfEmotions.isEmpty
is using the built-in isEmpty
method along with the !
operator to check if the array is not empty. As our array, arrayOfEmotions
is not empty, the expression will return true
making our condition fulfilled. As a result, the statement on line 3 is executed, replacing the value of the first element "happy"
with "joyful"
.
Try running the same code using an empty array and compare your output with the output we got in the example above.
In the next lesson, we will continue our discussion on if
and see what makes a Scala if
different from if
expressions in other programming languages.