Discuss the use and benefits of Pattern Matching in Scala, including the match expression.

Instruction: Provide examples to explain how pattern matching offers more powerful and expressive options compared to traditional control structures.

Context: This question explores the candidate's understanding of Scala's pattern matching feature, which is a powerful tool for decomposing data structures and performing conditional execution based on the structure of data. Candidates should discuss how pattern matching provides a more readable and concise way to handle conditional logic compared to if/else statements and the benefits it brings in terms of code safety and readability. Examples should include simple pattern matches, matching on case classes, and using guards.

Updated

A match expression evaluates its selector and chooses the first matching case whose guard succeeds. Patterns can test literals, bind values and decompose case-class fields. The chosen branch supplies the expression's result.

sealed trait Message
final case class TextMessage(content: String) extends Message
final case class ImageMessage(url: String, caption: String) extends Message

def dayLabel(day: String): String = day match {
  case "Monday" => "Start of the work week"
  case "Friday" => "End of the work week"
  case other => s"Other day: $other"
}
def describe(message: Message): String = message match {
  case TextMessage(content) if content.isEmpty => "Empty text"
  case TextMessage(content) => s"Text: $content"
  case ImageMessage(url, caption) => s"Image: $url, caption: $caption"
}
@main def patternExample(): Unit = {
  assert(dayLabel("Saturday") == "Other day: Saturday")
  assert(describe(TextMessage("")) == "Empty text")
  assert(describe(TextMessage("Hi")) == "Text: Hi")
  assert(describe(ImageMessage("image.png", "A cat")) == "Image: image.png, caption: A cat")
}

The unguarded text case handles values for which the first text guard is false. Ordering matters: placing it first would make the guarded case unreachable. The sealed hierarchy helps the compiler check coverage; relevant warnings can be made errors with -Werror. An incomplete match can still throw MatchError if it runs, and wildcard cases can hide the need to handle a new alternative explicitly. Pattern matching

This can express structural branching more directly than repeated casts and field tests. It does not validate every field: the example expects non-null messages and text, and it does not validate an image URL. Keep guards predictable and validate external data at the boundary.

Related Questions