Topic Overview

Welcome! Today, we're exploring Scala's special instructions: Conditional Looping, along with constructs that offer similar capabilities to Scala's break and continue. We know that loops enable code execution multiple times. Conditional looping, combined with Scala's powerful control constructs, enhances loop control, leading to flexible, efficient code. Put on your explorer's hat, and let's get started!

The 'if' Statement

Scala's if statement sets condition-based actions for your code. Consider this straightforward example where the if statement determines which message to print based on the value of temperature:

object Solution {
  def main(args: Array[String]): Unit = {
    val temperature = 15

    if (temperature > 20) {
    println("Wear light clothes.") // This will print if temperature is over 20.
    } else {
    println("Bring a jacket.") // This will print otherwise.
    }
  }
}

We can also evaluate multiple conditions using else if. In other words, "If the previous condition isn't true, then check this one":

object Solution {
  def main(args: Array[String]): Unit = {
    if (temperature > 30) {
      println("It's hot outside!") // Prints if temperature is over 30.
    } else if (temperature > 20) {
      println("The weather is nice.") // Prints if temperature is between 21 and 30.
    } else {
      println("It might be cold outside.") // Prints if temperature is 20 or below.
    }
  }
}
The 'break' Statement

Scala doesn't have a direct break statement, but we can achieve similar functionality using scala.util.control.Breaks. Here’s how you can exit a loop prematurely when a condition is met:

import scala.util.control.Breaks._

object Solution {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 3, 7, 9, 12, 15)

    breakable {
      for (number <- numbers) {
        if (number % 2 == 0) {
          println(s"The first even number is: $number") // Prints the first even number.
          break // Exits the loop after printing the first even number.
        }
        println(s"Number: $number")
      }
    }
    // Prints:
    // Number: 1
    // Number: 3
    // Number: 7
    // Number: 9
    // The first even number is: 12
  }
}
Alternatives to the 'continue' Statement
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal