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

I've noticed a recurring pattern when developers first encounter PartialFunction in Scala. They usually think, "Oh, this is just a regular function that might throw an exception or return None if the input is wrong."

Thinking it's just a function that throws exceptions

If you think of a PartialFunction as just a "risky" function, you're missing the entire point. Let's look at a standard function that only handles positive numbers:

def onlyPositives(n: Int): String = {
  if (n > 0) "Positive!" 
  else throw new IllegalArgumentException("Negative number!")
}

To a caller, this looks like a function that takes any Int. There is no way for the caller to know if onlyPositives can handle a specific value without actually calling it and risking a crash. That's a "total function" that happens to fail. It's a black box.

The magic of isDefinedAt

A PartialFunction is different because it's honest. It doesn't just perform a transformation; it carries a built-in mechanism to tell you, "Yes, I can handle this specific input," or "No, I cannot."

This is made possible by the isDefinedAt method. When you define a PartialFunction using case blocks, Scala automatically implements this method for you. Check this out:

val positiveOnly: PartialFunction[Int, String] = {
  case n if n > 0 => s"Positive $n"
}

println(positiveOnly.isDefinedAt(10))  // true
println(positiveOnly.isDefinedAt(-5))  // false

I find this distinction crucial because it allows the function to be composable. Because the function knows its own domain, other parts of the Scala library can query it before trying to execute it. You aren't just guessing and catching exceptions; you're checking capabilities.

Filtering and transforming with collect

The most common place you'll actually use this in a professional codebase isn't by calling isDefinedAt manually, but by using collect. You've likely used filter followed by map. While that works, it's inefficient because it traverses the collection twice.

collect takes a PartialFunction. It uses isDefinedAt to ignore the elements that don't match your case statements and applies the transformation to the ones that do, all in a single pass.

Imagine we have a list of raw logs, and we only care about the "ERROR" ones to extract their messages:

val logs = List(
  "INFO: System started",
  "ERROR: Database connection failed",
  "DEBUG: Heartbeat sent",
  "ERROR: Out of memory"
)

val errors = logs.collect {
  case s if s.startsWith("ERROR:") => s.stripPrefix("ERROR: ")
}

// Result: List(" Database connection failed", " Out of memory")

If I had used map here, I would have had to return an Option (like Some(msg) or None) and then flatten the result. collect is just cleaner. It lets you say: "Only give me the things that look like this, and turn them into that."




📋 Practical Task

Building a Smart Command Router

You are building a simple CLI tool. You receive a list of user input strings, but some are valid commands and some are just noise. You need to process these inputs efficiently.

Your Task:

  1. Create a list of strings called inputs containing a mix of valid commands (e.g., "HELP", "QUIT", "START 1") and invalid noise (e.g., "hello", "12345", "!!!").
  2. Define a PartialFunction[String, String] that:
    • Maps "HELP" to "Displaying help menu..."
    • Maps "QUIT" to "Shutting down..."
    • Uses a regex or startsWith to map any string starting with "START " to "Starting process with ID..." (including the ID from the string).
  3. Use the collect method on your inputs list to apply this partial function, ensuring that all "noise" strings are silently discarded.
  4. Print the resulting list of processed command responses.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.