Pattern Matching in Scala: A Complete Guide
Scala pattern matching example using match expressions, case classes, and sealed traits for structured programming
Pattern matching is one of the most powerful features of Scala, offering a more concise and readable way to handle conditional logic. It is similar to switch-case statements in other languages but far more expressive, allowing developers to match against constants, variables, types, and even complex data structures.
In this guide, we will explore pattern matching in Scala with practical examples and best practices.
Pattern matching is done using the match
keyword. Let’s start with a simple example.
package com.developerIndian.patternmatching
object DemoNumToString {
def main(args: Array[String]): Unit = {
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "other"
}
println(matchTest(3)) // Output: other
println(matchTest(1)) // Output: one
}
}
matchTest
takes an integer and returns a corresponding string._
(wildcard) is used as a default case to match any unmatched values.Case classes allow us to match more complex structures easily.
package com.developerIndian.patternmatching
trait Shape
case class Circle(radius: Double) extends Shape
case class Rectangle(height: Double, width: Double) extends Shape
case class Triangle(base: Double, height: Double) extends Shape
object DemoPatternMatching {
def myMatch(shape: Shape): String = shape match {
case shape: Circle => "This is a circle"
case shape: Rectangle => "This is a rectangle"
case shape: Triangle => "This is a triangle"
}
def main(args: Array[String]): Unit = {
val circle = Circle(100)
val rectangle = Rectangle(100, 200)
println(myMatch(rectangle)) // Output: This is a rectangle
}
}
Shape
trait and three case classes: Circle
, Rectangle
, and Triangle
.match
expression identifies the type of shape and returns the corresponding string.
Using sealed
traits ensures that all subclasses are known at compile-time, making pattern matching safer.
package com.developerIndian.patternmatching
sealed trait Device
case class Phone(model: String) extends Device {
def screenOff = "Turning screen off"
}
case class Computer(model: String) extends Device {
def screenSaverOn = "Turning screen saver on..."
}
object PatternMatching2 {
def myDeviceMatch(device: Device): String = device match {
case p: Phone => p.screenOff
case c: Computer => c.screenSaverOn
}
def main(args: Array[String]): Unit = {
val phone = Phone("mymodel")
println(myDeviceMatch(phone)) // Output: Turning screen off
}
}
sealed trait Device
to ensure all subclasses are within the same file.match
is used to determine if the Device
is a Phone
or Computer
, calling the respective method.if-else
statements._
) to handle unexpected values.sealed
traits when defining pattern-matching hierarchies.
Pattern matching in Scala is a powerful feature that simplifies complex conditional logic. Whether working with numbers, case classes, or sealed traits, Scala’s match
expression provides an elegant and type-safe way to handle various scenarios.
By mastering pattern matching, you can write more readable, maintainable, and efficient Scala applications. Try using pattern matching in your projects and see how it enhances your coding experience!