Scala Lesson 15 – Pattern Matching | Dataplexa

Pattern Matching in Scala

In this lesson, you will learn about pattern matching in Scala. Pattern matching is a powerful feature used to compare values against patterns and execute code based on the match.

It is similar to switch statements in other languages, but far more expressive and flexible.


Why Pattern Matching Is Important

Pattern matching allows you to write:

  • Cleaner and more readable code
  • Safer logic without complex if-else chains
  • Explicit handling of all possible cases

It is widely used in real-world Scala applications.


Basic Pattern Matching Syntax

Pattern matching uses the match keyword.

val number = 3

number match {
  case 1 => println("One")
  case 2 => println("Two")
  case 3 => println("Three")
}

Each case checks a condition and executes when a match is found.


Using Default Case

A wildcard case (_) is used when no other cases match.

val value = 10

value match {
  case 5  => println("Five")
  case 10 => println("Ten")
  case _  => println("Unknown value")
}

The wildcard ensures your code handles unexpected values.


Pattern Matching with Expressions

Pattern matching returns a value, so it can be used as an expression.

val day = 1

val result = day match {
  case 1 => "Monday"
  case 2 => "Tuesday"
  case _ => "Other day"
}

println(result)

This makes code concise and expressive.


Pattern Matching with Data Types

You can match based on the type of a value.

val data: Any = "Scala"

data match {
  case i: Int    => println("Integer")
  case s: String => println("String")
  case _         => println("Unknown type")
}

This is useful when working with mixed data types.


Pattern Matching with Multiple Conditions

You can use guards (if) inside pattern matching.

val age = 18

age match {
  case a if a < 18  => println("Minor")
  case a if a >= 18 => println("Adult")
}

Guards add additional conditions to patterns.


Pattern Matching with Tuples

Pattern matching works naturally with tuples.

val point = (3, 4)

point match {
  case (0, 0) => println("Origin")
  case (x, 0) => println(s"X-axis at $x")
  case (0, y) => println(s"Y-axis at $y")
  case (x, y) => println(s"Point at ($x, $y)")
}

Pattern Matching with Options

Pattern matching is commonly used with Option.

val value: Option[Int] = Some(10)

value match {
  case Some(v) => println(s"Value: $v")
  case None    => println("No value")
}

This ensures safe handling of missing values.


Pattern Matching with Case Classes

Case classes work seamlessly with pattern matching.

case class Person(name: String, age: Int)

val p = Person("Alice", 25)

p match {
  case Person(name, age) =>
    println(s"Name: $name, Age: $age")
}

This makes data extraction easy and readable.


Why Pattern Matching Is Powerful

Pattern matching helps Scala code stay:

  • Concise
  • Type-safe
  • Easy to maintain

It is a core feature used throughout the Scala ecosystem.


📝 Practice Exercises


Exercise 1

Use pattern matching to print a message based on an integer value.

Exercise 2

Create a tuple and match different cases.

Exercise 3

Use pattern matching to handle Option[String].


✅ Practice Answers


Answer 1

val n = 2

n match {
  case 1 => println("One")
  case 2 => println("Two")
  case _ => println("Other")
}

Answer 2

val pair = (1, 2)

pair match {
  case (1, 1) => println("Both ones")
  case (1, y) => println(s"First is 1, second is $y")
  case _      => println("Other pair")
}

Answer 3

val text: Option[String] = None

text match {
  case Some(t) => println(t)
  case None    => println("No text")
}

What’s Next?

In the next lesson, you will learn about Case Classes, which work closely with pattern matching and make data modeling easier.