Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
21: Partial Functions
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:
- Create a list of strings called
inputscontaining a mix of valid commands (e.g.,"HELP","QUIT","START 1") and invalid noise (e.g.,"hello","12345","!!!"). - Define a
PartialFunction[String, String]that:- Maps
"HELP"to"Displaying help menu..." - Maps
"QUIT"to"Shutting down..." - Uses a regex or
startsWithto map any string starting with"START "to"Starting process with ID..."(including the ID from the string).
- Maps
- Use the
collectmethod on yourinputslist to apply this partial function, ensuring that all "noise" strings are silently discarded. - Print the resulting list of processed command responses.
There are no comments for now.