Pattern Matching in Scala: A Complete Guide

3/19/2025

Scala pattern matching example using match expressions, case classes, and sealed traits for structured programming

Go Back

Pattern Matching in Scala: A Complete Guide

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.

Basic Pattern Matching in Scala

Pattern matching is done using the match keyword. Let’s start with a simple example.

Example 1: Matching Numbers to Strings

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
  }
}

Explanation

  • matchTest takes an integer and returns a corresponding string.
  • _ (wildcard) is used as a default case to match any unmatched values.
Scala pattern matching example using match expressions, case classes, and sealed traits for structured programming

Pattern Matching with Case Classes

Case classes allow us to match more complex structures easily.

Example 2: Matching Shapes

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
  }
}

Explanation

  • We define a Shape trait and three case classes: Circle, Rectangle, and Triangle.
  • The match expression identifies the type of shape and returns the corresponding string.

Pattern Matching with Sealed Traits

Using sealed traits ensures that all subclasses are known at compile-time, making pattern matching safer.

Example 3: Matching Devices

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
  }
}

Explanation

  • We use 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.

Benefits of Pattern Matching in Scala

  1. Improves Readability – Code is more concise and expressive compared to multiple if-else statements.
  2. Type Safety – The compiler ensures that all cases are handled.
  3. Extensibility – Easily scalable with case classes and sealed traits.
  4. Powerful Matching – Can match constants, variables, and even extract values from objects.

Best Practices for Pattern Matching

  • Always include a default case (_) to handle unexpected values.
  • Use sealed traits when defining pattern-matching hierarchies.
  • Avoid deep nesting; refactor complex patterns into separate functions.
  • Leverage case classes for better structure and maintainability.

Conclusion

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!