Table of Contents
Scala offers various mechanisms for controlling code flow. Let’s explore them here.
If/Else/then
Imagine you are building a charging station for electric vehicles. The station accepts only electric vehicles and they must have a battery capacity greater than 11Kwh.
The following code demonstrates this scenario:
def isChargeable(isElectric: Boolean, capacity: Int): Boolean =
if (!isElectric) then return false
if (capacity < 11) then false else trueOf course, in production code, you can simplify the function like this:
def isChargeableImproved(isElectric: Boolean, capacity: Int): Boolean =
isElectric && capacity > 11Else if
In a multiple branching scenario, you can use else if.
Imagine you need to classify players in a video game based on their experience point. The structure is something like this:
- < 100 points -> Rookie
- 100 < point < 1000 -> Amateur
- 1000 < point -> Professional
def rankPlayer(point : Int): String =
if (point < 100) then "Rookie"
else if (point < 1000) then "Amateur"
else "Professional"The following code would produce three levels from Rookie to Professional:
def main(args: Array[String]): Unit = {
println(rankPlayer(50))
println(rankPlayer(150))
println(rankPlayer(2550))
}
Pattern matching
If you come from languages like Java, you should be familiar with switch/case.
Scala has a similar structure called pattern matching.
Let’s consider a quick example:
def patternMatchingFood(isHungry: Boolean): Unit =
isHungry match
case true => println("Let's eat")
case false => println("Let's not eat")
Running the code would return the expected results:
def main(args: Array[String]): Unit = {
patternMatchingEat(true)
patternMatchingEat(false)
}

Let’s consider another example where we need a more complicated use of pattern matching. Let’s say you need to prepare a menu for a half-vegan guy. Here are the requirements
| Weekday | What to eat |
| Monday | Meat |
| Friday | Meat |
| Tuesday | Fruits |
| Thursday | Vegetables |
| Other days | Eat nothing (fasting) |
This piece of code implements the requirements:
def whatToEat(day: String): String =
day match
case "Monday" | "Friday" => "Meat"
case "Tuesday" => "Fruits"
case "Thursday" => "Vegetables"
case otherDay => s"I don't eat nothing on $otherDay"As you can see, you can group multiple matches in one case expression. You can also assign a variable and use it using in the return statement (otherDay).
Let’s run the function with some input. You should get the expected results:
def main(args: Array[String]): Unit = {
println(whatToEat("Monday"))
println(whatToEat("Friday"))
println(whatToEat("Tuesday"))
println(whatToEat("Thursday"))
println(whatToEat("Wednesday"))
println(whatToEat("Sunday"))
println(whatToEat("Invalid day"))
}

Conclusion
In this post, you have learned the basics of Scala control structures. The source code of this post is available on Github.

I build softwares that solve problems. I also love writing/documenting things I learn/want to learn.
