Introduction to Conditional Statements

Welcome! Today, we're delving into the world of conditional statements in programming through the lens of Scala. To relate this to a real-world example, consider a traffic signal that shows different colors to manage vehicular flow — green for go, and red for stop. Similarly, Scala uses conditional statements to control the flow of execution in programs.

In Scala, we utilize if and match-case expressions to aid in decision-making. Here is an example of a simple if statement:

@main def run: Unit =
    var lightColor = "green"
    if lightColor == "green" then
        println("Cars can go.") // Output: "Cars can go."
    else
        println("Cars should stop.")

Indentations matter in Scala, so ensure your code blocks are correctly indented to maintain readability and structure.

Understanding the "if" Expression

In Scala, the if statement is utilised to evaluate a condition. If the condition holds true, a specific block of code is executed. Consider an example where we verify whether a person with the age of 20 is an adult:

@main def run: Unit =
    val age = 20
    if age >= 18 then
        println("You are an adult.") // Output: "You are an adult."

In this instance, "You are an adult." is printed because our age, 20, is greater than or equal to 18.

"If-else" and "if-else-if-else" Constructs

Scala provides constructs like if-else and if-else-if-else, which enable the conditional execution of code blocks based on various conditions. For instance, consider a game where players win a prize if they score more than 70 points; those who score 70 or less don't win:

@main def run: Unit =
    val score = 65
    if score > 70 then
        println("Congratulations! You've won a prize.")
    else
        println("Better luck next time. Keep practicing.") // Output: "Better luck next time. Keep practicing."

For more complex scenarios, such as a quiz game in which different prizes (bronze, silver, gold) are won based on scores, you would use the if-else-if-else construct:

@main def run: Unit =
    val score = 65
    if score > 90 then
        println("Congratulations! You've won a gold prize.")
    else if score > 80 then
        println("Congratulations! You've won a silver prize.") 
    else if score > 70 then
        println("Congratulations! You've won a bronze prize.")
    else
        println("You've won a participation prize. Keep practicing.")

This example illustrates how Scala evaluates multiple conditions in an if-else-if-else structure, selecting and executing the first true condition, while ignoring the rest.

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