Let’s look at the control flow of a while loop below.
The above flow is showing that if the condition has been fulfilled, the compiler will execute the block of code and check the condition again. This loop will occur until the condition is not fulfilled in which case the compiler will exit the block of code.
Syntax
Before we see the while loop in action, let’s go over the syntax and see how to write a block of code with while using Scala.
The syntax is pretty straight forward with a while followed by the condition to be checked in () which is further followed by curly brackets {} in which appears the block of code to be executed if the condition holds true.
The condition must be an expression of type Boolean. If the condition is true, the code will execute. If the condition is false, the compiler will exit the code.
while in Action
In the example below, we want to print the numbers from 1 to 10 using a while loop.
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.
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 is true, the code will execute. If the condition is false, 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.