Skip to Content
Course content

41: Common Scala Interview Questions on Pattern Matching

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

A few years ago, I was interviewing a candidate for a senior Scala role. He was technically brilliant and breezed through the algorithmic challenges, but we hit a wall when I asked him how the compiler actually "knows" when a pattern match is exhaustive. He gave a vague answer about "Scala magic," and when I pressed him on the role of the sealed keyword, he stumbled. It was a classic case of knowing how to use the syntax without understanding the mechanics under the hood. In a high-stakes interview, that's the difference between looking like a developer who learned a few tutorials and someone who truly understands the type system.

The Exhaustiveness Trap and Sealed Traits

One of the most common interview questions involves why we use sealed traits. If you're asked this, don't just say "it limits inheritance." The real answer is about the compiler's ability to perform exhaustiveness checking. When you mark a trait as sealed, you're telling the Scala compiler that all implementations of this trait are defined in the current file. This allows the compiler to look at your match block and warn you—at compile time—if you've forgotten a case.

sealed trait PaymentMethod
case class CreditCard(number: String, cvv: String) extends PaymentMethod
case class PayPal(email: String) extends PaymentMethod
case class Crypto(walletAddress: String) extends PaymentMethod

def processPayment(method: PaymentMethod): String = method match {
  case CreditCard(n, _) => s"Charging card $n"
  case PayPal(e) => s"Redirecting to $e"
  // If I omit Crypto here, the compiler gives a warning: 
  // "match may not be exhaustive. It would fail on the following input: Crypto(_)"
}

In an interview, I'd recommend mentioning that this turns a potential runtime MatchError into a compile-time warning. That's the "senior" way to frame the answer: you're talking about safety and reliability, not just syntax.

Demystifying the unapply Method

Interviewers love to ask how case classes actually work during pattern matching. They want to hear the word unapply. Most developers think pattern matching is some built-in language magic, but it's actually just a call to an unapply method. When you write case CreditCard(number, cvv), Scala is actually calling CreditCard.unapply(method), which returns an Option containing the extracted values.

I've seen candidates get tripped up when asked if you can implement pattern matching for a class that isn't a case class. The answer is yes—you just have to write your own extractor object. This is a great way to show off your deeper knowledge. You can create an object with an unapply method to "deconstruct" a regular class or even a string, effectively creating your own custom matching logic that hides the internal complexity of the object being matched.

Guards and the Order of Evaluation

Finally, be prepared to discuss "guards"—those if expressions inside a case statement. A common pitfall is forgetting that patterns are evaluated from top to bottom. If you have a general case above a specific case with a guard, the general case will always win, and the guarded case will be dead code.

val age = 25
age match {
  case x if x > 18 => "Adult" 
  case 25 => "Exactly twenty-five" // This will NEVER be reached
}

I usually tell my mentees to treat guards as a last resort. If you can represent your logic using a sealed hierarchy (like the PaymentMethod example), do that instead. It's more type-safe and allows the compiler to help you. Guards are powerful, but they are essentially "invisible" to the exhaustiveness checker, meaning they can sneak MatchErrors back into your production code if you aren't careful.




📋 Practical Task

Building a Custom Extractor for a Legacy Payment String

In this exercise, you will simulate a real-world scenario where you have to handle "legacy" data. You have a system that receives payment identifiers as strings in the format "TYPE:ID" (e.g., "CC:12345" or "PP:user@email.com"). Instead of manually splitting these strings everywhere in your code, you are tasked with creating a custom extractor object.

Requirements:

  • Create an object named PaymentExtractor.
  • Implement an unapply method in PaymentExtractor that takes a String and returns an Option[(String, String)].
  • The unapply method should split the input string by the colon (:). If the string does not contain a colon, it should return None.
  • Write a test function that uses a match block to handle three cases:
    1. When the string matches PaymentExtractor("CC", id), print "Processing Credit Card with ID: [id]".
    2. When the string matches PaymentExtractor("PP", email), print "Processing PayPal with Email: [email]".
    3. A fallback case for any other format, printing "Invalid Payment Format".
Rating
0 0

There are no comments for now.

to be the first to leave a comment.