Scala Control Structures

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 true

Of course, in production code, you can simplify the function like this:

  def isChargeableImproved(isElectric: Boolean, capacity: Int): Boolean =
    isElectric && capacity > 11

Else 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))
  }
If, else if, then in action
If, else if, then in action

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)
  }
Running simple pattern matching in Scala
Running simple pattern matching in Scala

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

WeekdayWhat to eat
MondayMeat
FridayMeat
TuesdayFruits
ThursdayVegetables
Other daysEat nothing (fasting)
Half-vegan diet plan

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"))
  }
Running pattern matching function
Running pattern matching function

Conclusion

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

Leave a Comment