Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Control Structures in Scala

Introduction

Control structures are fundamental components of programming languages that dictate the flow of execution based on certain conditions or the state of the program. In Scala, control structures include conditionals, loops, and pattern matching.

Conditional Statements

Conditional statements allow you to execute different code based on certain conditions. In Scala, the primary conditional statements are if, else, and else if.

Example of Conditional Statements

Here is a simple example of using if and else:

val number = 10
if (number > 0) {
    println("Positive number")
} else {
    println("Negative number or Zero")
}
Output: Positive number

Nested Conditional Statements

You can also nest conditional statements to handle multiple conditions. This can be achieved using else if.

Example of Nested Conditionals

val number = 0
if (number > 0) {
    println("Positive number")
} else if (number < 0) {
    println("Negative number")
} else {
    println("Zero")
}
Output: Zero

Switch Case Statement

Scala also provides a match statement, which serves as a more powerful version of the traditional switch-case statement found in many other languages. It allows for more complex pattern matching.

Example of Match Statement

val day = 3
day match {
    case 1 => println("Monday")
    case 2 => println("Tuesday")
    case 3 => println("Wednesday")
    case _ => println("Other day")
}
Output: Wednesday

Loops

Loops are control structures that repeat a sequence of instructions until a certain condition is met. Scala provides several types of loops, including for, while, and do while.

For Loop

The for loop is commonly used for iterating over collections.

Example of For Loop

for (i <- 1 to 5) {
    println(i)
}
Output: 1 2 3 4 5

While Loop

The while loop continues to execute as long as a specified condition is true.

Example of While Loop

var i = 1
while (i <= 5) {
    println(i)
    i += 1
}
Output: 1 2 3 4 5

Do While Loop

The do while loop is similar to the while loop, but it guarantees that the loop will execute at least once.

Example of Do While Loop

var i = 1
do {
    println(i)
    i += 1
} while (i <= 5)
Output: 1 2 3 4 5

Conclusion

Control structures are essential for building logical flow in your Scala programs. Understanding how to use conditionals and loops effectively will enhance your programming skills and allow you to develop more complex and functional applications.