Scala improves upon basic conditional statements in a number of ways. Here are a few of the main points in understanding how to write conditional statements in Scala.
If Statements
If expressions have values. This is actually a very useful mechanism. Similar to the last statement in a function, an if-else statement returns the value of the expression that follows the if-else. For example, the following if-statement has a value of true or false depending on the value of x.
if (x < 10) true else false
You can actually initialize a variable with the result of this expression if you want.
val result = if (x < 10) {
true
}
else {
false
}
Match Statements
We don't have traditional switch-case statements in Scala, but to no surprise, there's something even better. Scala's "match" expressions are an improved switch statement. Here's an example of a "match" expression that sets the value of a variable "n" based on the value of a variable named "number". If number is 0, then n becomes "zero". If number is 1, then n becomes "one". If number is any other value, then n becomes "some other value".
val n = number match {
case 0 => "zero"
case 1 => "one"
case _ => "some other value"
}
There's no ability for fall-through to occur, like can often happen in a traditional switch statement. Rarely, do you want fall-through, but if you do need to have a range of values evaluate to the same result, you can do that with a "guard". For example, we can modify our match expression to match values of 0, 1, 10-20, and 30-50. Anything else is caught with our "case _" and will result in a value of "some other value". The guard can be any Boolean condition.
val n = number match {
case 0 => "zero"
case 1 => "one"
case num if 10 until 20 contains num => "between ten and twenty"
case num if 30 until 50 contains num => "between thirty and fifty"
case _ => "some other value"
}
No comments:
Post a Comment