Skip to Content
Course content

163: Common Scala Interview Questions on Pattern Matching Revisited

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I remember mentoring a developer a few years back who was interviewing for a senior role at a high-frequency trading firm. He was brilliant with algorithms, but he hit a wall when the interviewer asked him to write a function that handled a List[T] differently depending on whether it contained Strings or Integers. He confidently wrote a match block with case list: List[String] => ... and case list: List[Int] => .... He was baffled when the compiler screamed at him. He spent ten minutes trying to "fix" the syntax, not realizing he was fighting a fundamental JVM limitation: type erasure. It was a humbling moment, but it's exactly why we need to revisit the "interview" side of pattern matching—because the gaps between "it works in a tutorial" and "it works in production" are usually where the hardest questions live.

The Type Erasure Trap

When you're in an interview, if someone asks you to match on a generic collection, your internal alarm should go off. Because of type erasure, the JVM doesn't actually know what's inside a List at runtime. To the JVM, a List[String] and a List[Int] are both just List. If you try to match on the specific generic type, you'll get a compile-time error telling you that the match is "unrefined."

I usually tell people that the "correct" interview answer involves mentioning TypeTag or ClassTag, but the "software engineer" answer is to avoid the pattern entirely. Instead of matching on the list type, match on the elements of the list. For example, matching on case head :: tail and then checking the type of the head is often a safer, more idiomatic way to handle this without fighting the compiler. It's a subtle distinction, but it shows you actually understand how the Scala compiler maps to the bytecode.

Exhaustiveness and the Sealed Trait Guarantee

You've likely used sealed traits before, but in an interview context, the question isn't just "what is it?" but "why does it matter for pattern matching?" The magic here is the compiler's ability to perform exhaustiveness checking. If you have a sealed trait Shape with Circle and Square, and you forget to handle Square in your match block, the compiler gives you a warning.

Now, here is the nuance: if you use a default case (the dreaded case _ =>), you effectively silence that warning. I've seen developers do this as a "safety net" to avoid MatchError, but in a professional codebase, that's often a mistake. By adding a catch-all, you're telling the compiler, "Stop helping me." If you add a Triangle to your Shape trait six months from now, you won't get a single compiler warning telling you where your logic is now incomplete. You'll just get a generic behavior (or a bug) at runtime. I always advocate for removing the catch-all case in sealed hierarchies to let the compiler act as your automated Todo list.

Custom Extraction with the Unapply Method

Most people stop at case classes, but if you want to impress in a technical deep-dive, you need to talk about unapply. This is what allows you to "deconstruct" an object that isn't necessarily a case class. Think of it as the inverse of a constructor. You're defining how an object should be ripped apart for a match block.

case class User(name: String, email: String)

object UserExtractor {
  def unapply(s: String): Option[(String, String)] = {
    val parts = s.split("@")
    if (parts.length == 2) Some((parts(0), parts(1))) else None
  }
}

// Now you can match on a raw string as if it were a User object
val input = "dev_scala@example.com"
input match {
  case UserExtractor(name, domain) => println(s"User $name is at $domain")
  case _ => println("Invalid format")
}

This pattern is incredibly powerful for validation. Instead of writing a bunch of if/else blocks to parse a string, you wrap that logic in an extractor. It keeps your business logic clean and your pattern matches readable. It's the difference between writing code that just "works" and writing code that is actually architected for growth.




📋 Practical Task

Implementing a Validated Social Security Number Extractor

In this exercise, you will implement a custom extractor to handle the validation and parsing of Social Security Numbers (SSNs). Instead of using a case class, you will create an object that uses the unapply method to ensure a string is in the correct format (XXX-XX-XXXX) before allowing it to be matched.

Requirements:

  • Create an object named SSNExtractor.
  • Implement an unapply method that takes a String and returns an Option[(String, String, String)] containing the three segments of the SSN.
  • The unapply method should only return Some if the string matches the regex pattern ^\d{3}-\d{2}-\d{4}$.
  • Write a test match block that takes a list of strings (some valid, some invalid) and uses SSNExtractor to print "Valid SSN: [segments]" for matches and "Invalid Format" for others.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.