WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Scala · Basic · question 5 of 100

What is pattern matching in Scala and why is it important?

📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

Pattern matching is a powerful feature in Scala that allows you to decompose and extract values from complex data structures by specifying patterns, which are similar to regular expressions for matching against values. It is an essential feature because it makes it easier to work with complex data and provides a more expressive and readable way of handling different cases in code, compared to traditional if-else or switch statements in other programming languages.

Pattern matching in Scala is implemented using the ‘match‘ keyword, which is followed by a series of ‘case‘ statements specifying the patterns and the code to execute for each matching pattern. Here’s a simple example of pattern matching on integers:

val x: Int = 3

x match {
  case 1 => println("One")
  case 2 => println("Two")
  case 3 => println("Three")
  case _ => println("Something else")
}

In this example, the value of ‘x‘ is matched against the patterns 1, 2, and 3. The code corresponding to the matching pattern is executed, and in this case, it will print "Three". The ‘_‘ symbol is a wildcard pattern that matches anything, and it’s used as a catch-all case.

Scala’s pattern matching is powerful because it supports different types of patterns:

1. **Constant patterns**: Match a specific value, such as a number, string, or object.

x match {
  case 42 => "The answer"
  case "hello" => "Greeting"
  case Math.Pi => "PI"
}

2. **Variable patterns**: Match any value and bind it to a variable.

x match {
  case n: Int => s"The number is $n"
  case s: String => s"The string is '$s'"
}

3. **Constructor patterns**: Match an object and extract its values using the case class constructor syntax.

sealed trait Expr

case class Num(value: Int) extends Expr
case class Add(lhs: Expr, rhs: Expr) extends Expr

val expression = Add(Num(1), Num(2))

expression match {
  case Num(x) => s"A number: $x"
  case Add(lhs, rhs) => s"An addition: $lhs + $rhs"
}

4. **Sequence patterns**: Match sequences (e.g., lists) of a specific length or extract elements at specific positions.

val list = List(1, 2, 3)

list match {
  case List(1, 2, 3) => "The list is 1, 2, 3"
  case List(first, _, _) => s"The first element is $first"
  case _ => "Unknown list"
}

5. **Tuple patterns**: Match tuples and extract their elements.

val pair = (1, 2)

pair match {
  case (a, b) => s"The pair is ($a, $b)"
}

6. **Typed patterns**: Match values by their type.

val value: Any = "Hello"

value match {
  case i: Int => "Integer"
  case s: String => "String"
  case _ => "Unknown type"
}

Pattern matching is important because it provides a way to handle different cases in a concise and expressive manner, which leads to cleaner and more maintainable code. It is particularly useful when working with algebraic data types (like case classes and sealed traits) and when implementing functions like recursive tree traversals, interpreters, and other tasks that require processing complex data structures.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Scala interview — then scores it.
📞 Practice Scala — free 15 min
📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

All 100 Scala questions · All topics