Choices
If
The if statement is a fundamental control flow mechanism in Scala, as in many other programming languages. It allows you to execute a block of code conditionally, depending on whether a Boolean expression evaluates to true or false. Scala's if statement is similar to that in Java, C, and many other languages, but with some functional programming twists that enhance its utility and flexibility.
Basic if Statement
The simplest form of an if statement in Scala is:
if condition then
// Block of code to execute if the condition is true
For example:
val age = 18
if age >= 18 then
println("You are an adult.")
This code checks if age is 18 or older and prints a message if the condition is true.
if-else Statement
The if-else statement extends the if statement by allowing you to execute an alternative block of code if the condition is false:
if condition then
// Block of code to execute if the condition is true
else
// Block of code to execute if the condition is false
For example:
if age >= 18 then
println("You are an adult.")
else
println("You are a minor.")
if-else if Ladder
For multiple conditions, Scala supports the if-else if ladder, similar to other languages:
if condition1 then
// Block of code for condition1
else if condition2 then
// Block of code for condition2
else
// Block of code if none of the above conditions are true
Example:
if age < 13 then
println("You are a child.")
else if age < 18 then
println("You are a teenager.")
else
println("You are an adult.")
if Expressions and Value Assignment
One of Scala's functional programming features is treating if-else as an expression that returns a value. This allows you to assign the result of an if-else directly to a variable:
val classification = if age < 13 then "child"
else if age < 18 then "teenager"
else "adult"
println(s"You are a $classification.")
This feature eliminates the need for the ternary operator (condition ? trueValue : falseValue) found in other languages, as if-else in Scala can be used in the same concise way.
Nested if Statements
if statements can be nested within each other to check multiple conditions:
val isSunny = true
val temperature = 25 // Celsius
if isSunny then
if temperature > 20 then
println("It's a nice day for a walk.")
else
println("It's cool outside, but sunny.")
else
println("It might rain today.")
Match
The match expression in Scala is a powerful feature that extends the concept of switch-case statements found in other languages. It allows you to match against a value, then execute a block of code depending on the match. Scala's match is more potent than a traditional switch-case because it can match types, values, patterns, and even guard expressions. It's a cornerstone of Scala's pattern matching capabilities, enabling concise and expressive code.
value match
case pattern1 => // Block of code for pattern1
case pattern2 => // Block of code for pattern2
// ...
case _ => // Block of code if none of the patterns match (default case)
Examples
Matching Simple Values
val dayOfWeek = 3
val dayName = dayOfWeek match
case 1 => "Sunday"
case 2 => "Monday"
case 3 => "Tuesday"
case 4 => "Wednesday"
case 5 => "Thursday"
case 6 => "Friday"
case 7 => "Saturday"
case _ => "Invalid day"
println(dayName) // Output: Tuesday
Multiple match
In Scala, the match expression can also be used to match multiple patterns and execute the same code for all matched patterns. This is done using the | operator.
val x: Int = 2
val result: String = x match
case 1 | 2 | 3 => "x is between 1 and 3"
case 4 | 5 | 6 => "x is between 4 and 6"
case _ => "x is outside the range"
println(result)
In this example, we use the | operator to match the value of x against multiple patterns. The code in the first block will execute if x is 1, 2, or 3. The code in the second block will execute if x is 4, 5, or 6. The code in the last block, which uses the underscore _ pattern, will execute if no other pattern matches.
Note that the | operator can be used with any pattern, including custom patterns.
Matching Types
def process(value: Any): Unit = value match
case s: String => println(s"String of length ${s.length}")
case i: Int => println(s"Integer: $i")
case _ => println("Unknown type!")
process("Hello")
process(123)
process(3.14)
Matching with Guards
You can add conditional expressions (guards) to your cases using if:
val number = 10
val parity = number match
case n if n % 2 == 0 => "even"
case _ => "odd"
}
println(parity) // Output: even
Tips for Using Match Expressions
- Exhaustiveness: Scala's compiler checks if the match cases are exhaustive, meaning all possible cases are covered. This helps prevent runtime errors.
- Default Case: Always provide a default case (
case _ =>) to handle unexpected values, unless you are sure the match cases are exhaustive. - Pattern Guards: Use guards to refine your match cases with additional conditions.