How To Use If Else Statement And Expression
Overview
In this tutorial, we will go over the if and else expressions. If you are coming from other languages such as Java or .NET, this should be familiar, but with one caveat!
In Scala, you can use the if and else clause as a statement to test for some condition or logical step. In addition, you can also use if and else clause as an expression where you get back the result of your condition or logical step.
Steps
1. Using if clause as a statement
Let's declare two immutable integer variables namely numberOfPeople and donutsPerPerson. For simplicity, we are using Scala's type inference when declaring the variables which we have seen in the previous Type Inference tutorial. We then check if the numberOfPeople is greater than 10 and will print the number of donuts to be bought.
println("Step 1: Using if clause as a statement")
val numberOfPeople = 20
val donutsPerPerson = 2
if(numberOfPeople > 10)
println(s"Number of donuts to buy = ${numberOfPeople * donutsPerPerson}")
NOTE:
- We are leveraging what we've learned from the Scala String Interpolation tutorial to help us build the String inside the println() function.
2. Using if and else clause as a statement
Now that we know how to write an if statement, let's extend the example from Step 1 and add an else clause to print a default number of donuts you need to buy if there is less that 10 persons.
println(s"\nStep 2: Using if and else clause as a statement")
val defaultDonutsToBuy = 8
if(numberOfPeople > 10)
println(s"Number of donuts to buy = ${numberOfPeople * donutsPerPerson}")
else
println(s"Number of donuts to buy = $defaultDonutsToBuy")
3. Using if, else if, and else clause as a statement
Let's extend once more our if statement to include and else if clause as follows:
println("\nStep 3: Using if, else if, and else clause as a statement")
if(numberOfPeople > 10) {
println(s"Number of donuts to buy = ${numberOfPeople * donutsPerPerson}")
} else if (numberOfPeople == 0) {
println("Number of people is zero.")
println("No need to buy donuts.")
} else {
println(s"Number of donuts to buy = $defaultDonutsToBuy")
}
NOTE:
- It's a good practice to enclose your if, else, else if statements with curly braces {} as they get more complex.
4. Using if and else clause as expression
What if you had to store the result of the if and else expressions above into a variable. With Scala, you can easily inline this as follows:
println("\nStep 4: Using if and else clause as expression")
val numberOfDonutsToBuy = if(numberOfPeople > 10) (numberOfPeople * donutsPerPerson) else defaultDonutsToBuy
println(s"Number of donuts to buy = $numberOfDonutsToBuy")
NOTE:
- In another language such as Java or .NET, you would have used the Ternary Operator to achieve Step 4.
- Perhaps Scala's functional style is much easier to read and less error prone compared to the ternary operator.
Summary
In this tutorial, we went over the following:
- How to use a simple if statement
- How to use an if and else statement
- How to use an if, else if and else statement
- How to use if and else clause as expressions which can be assigned to a variable
Tip
- In upcoming tutorials, we will go over pattern matching which is more popular in functional programming rather than using if and else expressions.
- By now you should have noticed that in Scala there is no need to terminate each statement with a semi-colon ;. If you are coming from Java or .NET it may take some time to get used to it. But this is yet another example of how Scala allows us to not over-clutter our code base and make it more readable!
Source Code
The source code is available on the allaboutscala GitHub repository.
What's Next
In the next tutorial, I will go over for loop constructs in Scala and show how you can apply filters on your for loops.
Stay tuned!