Scala Pattern Matching and Case Classes: Syntax, Examples, and Usage
This article explains Scala's powerful pattern matching mechanism, demonstrates matching on integers, strings, and types with code examples, compares it to Java's switch, and introduces case classes as special classes optimized for pattern matching, highlighting their automatically generated methods and usage.
Scala provides a powerful pattern matching mechanism that is widely used.
A pattern match consists of a series of alternatives, each starting with the case keyword, where a pattern and one or more expressions are separated by the arrow symbol => .
Below is a simple integer value pattern matching example:
object Test {
def main(args: Array[String]) {
println(matchTest(3))
}
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "many"
}
}Running the code produces the output:
$ scalac Test.scala
$ scala Test
manyThe match expression corresponds to Java's switch but is written after the selector expression, i.e., selector match { alternatives } . It evaluates each pattern in order and stops after the first matching case.
Another example demonstrates pattern matching with different data types:
object Test {
def main(args: Array[String]) {
println(matchTest("two"))
println(matchTest("test"))
println(matchTest(1))
println(matchTest(6))
}
def matchTest(x: Any): Any = x match {
case 1 => "one"
case "two" => 2
case y: Int => "scala.Int"
case _ => "many"
}
}Running this code yields:
$ scalac Test.scala
$ scala Test
2
many
one
scala.IntThe first case matches the integer 1, the second matches the string "two", the third uses a type pattern to check if the value is an Int, and the fourth is the default case, similar to default in a switch.
Case classes (defined with the case keyword) are special classes optimized for pattern matching. Example:
object Test {
def main(args: Array[String]) {
val alice = new Person("Alice", 25)
val bob = new Person("Bob", 32)
val charlie = new Person("Charlie", 32)
for (person <- List(alice, bob, charlie)) {
person match {
case Person("Alice", 25) => println("Hi Alice!")
case Person("Bob", 32) => println("Hi Bob!")
case Person(name, age) => println("Age: " + age + " year, name: " + name + "?")
}
}
}
case class Person(name: String, age: Int)
}Executing this code prints:
$ scalac Test.scala
$ scala Test
Hi Alice!
Hi Bob!
Age: 32 year, name: Charlie?When declaring a case class, the following happen automatically: each constructor parameter becomes a val (unless explicitly declared var), an apply method is added to the companion object, an unapply method is generated for pattern matching, and toString, equals, hashCode, and copy methods are provided unless overridden.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
