Scala Control Structures: Integrating Loops with Conditionals

Topic Overview

Welcome, learners! Let's delve deeper into Scala programming by combining loops and decision-making structures. We'll explore the potential of integrating loops, such as for and while, with conditional structures like if and match-case scenarios. These combinations can make our programs considerably more dynamic and flexible.

Understanding Conditional Constructs

Let’s first revisit the conditional constructs in Scala. You'll recall the if construct, which executes a block of code when a condition is met. For example:

Scala
val number = 10
if (number > 0) {
    println("The number is positive.") // This line is executed if the condition is true
}

Compound conditions, built with logical operators like && (AND) and || (OR), can also be used:

Scala
val number = 10
if (number > 0 && number <= 10) {
    println("The number is positive and less than or equal to 10.") // This line would be executed if both conditions are true
}

Next, let's review the match-case structure. Resembling a compact form of the if - else chains, the match-case matches its argument with different patterns:

Scala
val number = 1
number match {
    case 1 => println("One") // This line is executed because the number equals 1
    case 2 => println("Two")
    case _ => println("Invalid number")
}

Conditional Constructs within For Loop

We can combine conditional statements with loops. Here's an if construct within a for loop:

Scala
for (i <- 1 to 10) {
    if (i % 2 == 0) {
        println(s"$i is even.") // Prints that i is even if i is divisible by 2
    } else {
        println(s"$i is odd.") // Otherwise, prints that i is odd
    }
}

A for loop can also easily incorporate a match-case structure:

Scala
for (i <- 1 to 3) {
    i match {
        case 1 => println("One") // Prints "One" if i equals 1
        case 2 => println("Two") // Prints "Two" if i equals 2
        case _ => println("Three") // Prints "Three" for other values of i
    }
}

Conditional Constructs in While Loop

We can apply the same combined approach with while loops. Here's a while loop with an if construct:

Scala
var i = 1
while (i <= 10) {
    if (i % 2 == 0) {
        println(s"$i is even.") // Prints that i is even if i is divisible by 2
    } else {
        println(s"$i is odd.") // Otherwise, prints that i is odd
    }
    i += 1 // Increase i by 1 after each iteration
}

A while loop can also include a match-case structure:

Scala
var i = 1
while (i <= 3) {
    i match {
        case 1 => println("One") // Prints "One" if i equals 1
        case 2 => println("Two") // Prints "Two" if i equals 2
        case _ => println("Three") // Prints "Three" for other values of i
    }
    i += 1 // Increase i by 1 after each iteration
}
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