How To Use If Else Statement And Expression

By Nadim Bahadoor | Last updated: March 16, 2018 at 11:18 am

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:

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.

This concludes our tutorial on How To Use If Else Statement And Expression and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

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!

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Technology and Finance Consultant with over 14 years of hands-on experience building large scale systems in the Financial (Electronic Trading Platforms), Risk, Insurance and Life Science sectors. I am self-driven and passionate about Finance, Distributed Systems, Functional Programming, Big Data, Semantic Data (Graph) and Machine Learning.
Other allaboutscala.com tutorials you may like: