Scala Match and Case ExamplesUse match with cases to test the value of a variable and return another value.
dot net perls
Match. An Int is 3. A List has two special values at its start. In languages we often need to handle special cases based on the values in our data. Pattern matching is a solution.
With the match keyword, we begin a match construct. We use cases to indicate values to be matched. We can return values directly from cases.
Here we implement a function called colorCode. It accepts an id Int and returns a String. A match construct determines which string to return based on the Int.
Case We use the case-keyword to specify cases to return. Here we use simple cases for single Ints, but more complex forms may be used.
// Use match on parameter id and return a String.
// ... Default case returns "None" String.
Scala program that uses match
def colorCode(id: Int): String = id match
0 => "Blue"
1 => "Red"
2 => "Green"
_ => "None"
// Get color code for this argument.
val result = colorCode(0)
val result2 = colorCode(1)
val result3 = colorCode(4000)
List pattern matching.
To use pattern matching, we provide special syntax forms. For example, to match lists we specify three identifiers separated by "::" tokens.
Here The testList function matches lists with two or more elements, and returns true if the second element is greater than the first.
Tip The identifiers in the list pattern do not matter, but only the first two are elements we can compare.
Note The third identifier is the remainder of the list. So here "a" is element 1, "b" is element 2 and "c" is all remaining elements.
// Return true if list has two or more elements.
// Second element must be greater than the first.
// ... Return false for all other lists.
Scala program that uses match, list pattern
def testList(x: List[Int]): Boolean = x match
case a :: b :: c =>
b > a
case _ =>
// Call testList.
val result1 = testList(List(10, 20, 30))
val result2 = testList(List(20, 10))
val result3 = testList(List())
val result4 = testList(List(1, 0, 2, 3))
val result5 = testList(List(0, 1, 2, 3))
An option can be evaluated in match statement. An option is either Some value or is None. We can use Some and None in a match construct.
Here GetOption returns an Option that wraps an Int. If we pass 1 or greater, we get Some value. Otherwise we get None.
Result We pass 2 to getOption which returns a valid option. The Some case in the match block is reached. A value exists.
// Return Some or None option based on integer.
Scala program that uses Some, None option match
getOption(n: Int): Option[Int] = if (n >= 1) Some(n)
// Get an option.
val result = getOption(2
// Match option on Some and None.
=> println("Value exists"
=> println("Nothing exists"
If inside match case.
We can capture variables in cases and use if-statements to test those variables' values. These are guarded, conditional cases.
Here Our match tests the "magnitude" value. It handles the case of greater than or equal to 4, and the case of less than or equal to 1.
String This match construct returns a string. Its result is stored in the "result" value and then printed to the screen.
Scala program that uses match with if-expressions
val magnitude = 5
// Match on magnitude, returning a string.
// ... Handle greater than or equal to 4.
// Handle less than or equal to 1.
val result = magnitude match
m if m >= 4 => "Big, greater than or equal to 4"
m if m <= 1 => "Small, less than or equal to 1"
_ => "Medium"
// Print result.
Big, greater than or equal to 4
List pattern notes.
Let us research list pattern matching. We find that the pattern to match lists has three parts separated by "::" symbols.
Pattern Matching: scala-lang.org
The pattern x :: y :: xs matches lists of length >= 2,
binding x to the list's first element, y to the list's second element,
and xs to the remainder.
A tuple can be matched. The syntax is similar to a list pattern. We can require specific values in any part of the tuple being matched.
A review. Pattern matching is similar to a "switch" statement in C-like languages. But in Scala we can use more advanced patterns. This simplifies code and makes it clearer.
© 2007-2021 sam allen. send bug reports to email@example.com.