Lesson 7
Scala Conditional Expressions: Controlling Program Flow
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:

Scala
1@main def run: Unit = 2 var lightColor = "green" 3 if lightColor == "green" then 4 println("Cars can go.") // Output: "Cars can go." 5 else 6 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:

Scala
1@main def run: Unit = 2 val age = 20 3 if age >= 18 then 4 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:

Scala
1@main def run: Unit = 2 val score = 65 3 if score > 70 then 4 println("Congratulations! You've won a prize.") 5 else 6 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:

Scala
1@main def run: Unit = 2 val score = 65 3 if score > 90 then 4 println("Congratulations! You've won a gold prize.") 5 else if score > 80 then 6 println("Congratulations! You've won a silver prize.") 7 else if score > 70 then 8 println("Congratulations! You've won a bronze prize.") 9 else 10 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.

Utilizing `if-else` as an Expression

A key feature of Scala is the ability to use if-else as an expression. This enables you to return a value from a conditional check directly to a variable. Let's examine how this works:

Scala
1@main def run: Unit = 2 val age = 20 3 val status = if age >= 18 then "adult" else "minor" 4 println(s"You are an $status.") // Output: "You are an adult."

In this example, the if-else expression evaluates a condition and assigns the result directly to a variable. This makes your code more concise and enhances readability.

Introduction to the "match-case" Expression

Scala's match-case expression allows for clean and readable conditional logic. It sequentially evaluates conditions and executes the code block of the first matching branch, serving as an effective mechanism for handling multiple conditional paths.

Scala
1@main def run: Unit = 2 val score = 95 3 score match 4 case _ if score > 90 => println("Congratulations! You've won a gold prize.") 5 case _ if score > 80 => println("Great! You've won a silver prize.") 6 case _ if score > 70 => println("Good job! You've won a bronze prize.") 7 case _ => println("You've won a participation prize. Keep practicing.")
"match-case" Expression with Multiple Conditions

Scala enables the definition of multiple conditions within a single branch of a match-case expression:

Scala
1@main def run: Unit = 2 val score = 85 3 val participantNumber = 1000 4 (score, participantNumber) match 5 case (x, y) if y == 1000 || x > 90 => println("Congratulations! You've won a grand prize.") 6 case (x, _) if x > 70 => println("Good job! You've won a silver prize.") 7 case _ => println("You've won a participation prize. Keep practicing.")

In this code, participants can win a grand prize either by having a score greater than 90 or by having a lucky participant number of 1000. Even if their score is less than 90, they can still win the grand prize because of their lucky number. If the score is greater than 70 but doesn't qualify for the grand prize, they win a silver prize. All other cases receive a participation prize.

Using `match-case` with Predetermined Values

You can use the match-case expression to compare a variable against predefined values or conditions. For instance, to check if a number is odd or even:

Scala
1@main def run: Unit = 2 val number = 4 3 val remainder = number % 2 4 remainder match 5 case 0 => println(s"$number is even") 6 case 1 => println(s"$number is odd") 7 case _ => println("This is an unexpected case")
`match-case` as an Expression

In Scala, match-case not only controls flow, but it can also be used as an expression to return values:

Scala
1@main def run: Unit = 2 val status = 85 3 val result = status match 4 case x if x >= 0 && x <= 59 => "Fail" 5 case x if x >= 60 && x <= 79 => "Pass" 6 case _ => "Excellent" 7 println(s"Result: $result") // Output: "Result: Excellent"
Lesson Summary

Congratulations on completing this lesson. You've learned about if and match-case expressions in Scala, and how they're applied to manage decision-making and flow control. Next, you'll have an opportunity to apply what you've learned through hands-on exercises. Practice is key in programming. Keep up the good work!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.