Scala Loops Essentials: Exploring For and While Loops with Collections

Topic Overview and Actualization

Hello, Explorer! Today, we will dive into the world of Scala loops, pivotal constructs that streamline repetitive tasks. Picture loops as a marathon of TV series episodes. We will explore the Scala looping universe and gain hands-on experience by applying loops to collections like Lists and Strings.

Understanding Looping

Have you ever experienced repeating a favorite song on a loop? That's what loops are all about in programming too. For instance, you can print greetings for a list of friends using a for loop in Scala:

object Solution {
  def main(args: Array[String]): Unit = {
    val friends = List("Alice", "Bob", "Charlie", "Daniel")
    // `friend` is the loop variable, taking each name in the `friends` list
    for (friend <- friends) {
        // for each `friend`, this line is executed
        println(s"Hello, $friend! Nice to meet you.")
    }
    /*
    Prints:
    Hello, Alice! Nice to meet you.
    Hello, Bob! Nice to meet you.
    Hello, Charlie! Nice to meet you.
    Hello, Daniel! Nice to meet you.
    */
  }
}

Loops allow us to automate repetitive sequences efficiently.

For Loop in Scala

In Scala, a for loop works with any sequence, like Lists or Strings. Let's print a range of numbers using a for loop:

object Solution {
  def main(args: Array[String]): Unit = {
    // `num` runs through each number in the range from 0 until 5 (exclusive)
    for (num <- 0 until 5) {
        // This line will print numbers from 0 to 4
        println(num)
    }
  }
}

Each loop iteration updates the variable (num) to the next sequence value before executing the code block.

While Loop in Scala

While loops execute code continuously until a condition becomes false. Here's a simple example:

object Solution {
  def main(args: Array[String]): Unit = {
    var num = 0
    // The loop keeps running until num is greater than or equal to 5
    while (num < 5) {
        println(num)
        // increase num by 1 each iteration
        num += 1
    }
  }
}

As you can see, before each iteration, Scala checks the condition (num < 5). If it's true, the code block runs; otherwise, Scala exits the loop.

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