-
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
48: Practice Exercise: Building a Type-Safe Configuration Loader
We've spent a lot of time talking about Either and Option in previous lessons, but the real magic happens when you use them to shield your application's core logic from the "messiness" of the outside world. A classic example is configuration. Most config files are just strings, but your business logic needs integers, booleans, and durations. If you just call .toInt on a config string and it's missing or malformed, your app crashes at startup with a stack trace that's a mile long.
I want to show you how to build a loader that transforms a raw map of strings into a type-safe case class, ensuring that if anything is wrong, we get a clean list of errors instead of a crash.
Defining the Target Shape
First, let's define what we actually want. I'm building a simple database configuration. I don't want to pass a Map around my whole app; I want a dedicated case class. It's cleaner and makes the code self-documenting.
case class DbConfig(
host: String,
port: Int,
timeoutMs: Int
)
Now, I need a way to represent what went wrong. A simple String for an error is usually enough for small projects, but I prefer a sealed trait so I can handle different error types programmatically if this grows.
sealed trait ConfigError
case class MissingKey(key: String) extends ConfigError
case class InvalidValue(key: String, value: String) extends ConfigError
Trying the "Quick and Dirty" Way
When I first started writing this, I tried to keep it simple. I wrote a helper to grab a value and just used .toInt for the numbers. It looked like this:
def loadConfig(raw: Map[String, String]): DbConfig = {
DbConfig(
host = raw("db.host"),
port = raw("db.port").toInt,
timeoutMs = raw("db.timeout").toInt
)
}
I quickly realized this is a disaster. If db.host is missing, I get a NoSuchElementException. If db.port is "eighty-eighty", I get a NumberFormatException. It's exactly the "crash at startup" scenario I wanted to avoid. I'm essentially just pushing the errors to the runtime.
Making the Extraction Type-Safe
To fix this, I need a helper method that returns an Either. Instead of throwing exceptions, it should return a Left(ConfigError). I'll write a generic helper that can handle the lookup and an optional transformation function (like toInt).
def getValue[T](raw: Map[String, String], key: String)(transform: String => T): Either[ConfigError, T] = {
raw.get(key) match {
case None => Left(MissingKey(key))
case Some(value) =>
try {
Right(transform(value))
} catch {
case _: Exception => Left(InvalidValue(key, value))
}
}
}
I used a try-catch block here. While some Scala purists might prefer Try().toEither, in a configuration loader, this is a pragmatic way to wrap the standard library's throwing converters.
Wiring it Together
Now I can assemble the DbConfig. Since I'm using Either, I can use a for-comprehension. This is great because it acts as a "short-circuit"—if the host is missing, it stops right there and returns the error without even trying to parse the port.
def loadDbConfig(raw: Map[String, String]): Either[ConfigError, DbConfig] = {
for {
host <- getValue(raw, "db.host")(identity)
port <- getValue(raw, "db.port")(_.toInt)
timeout <- getValue(raw, "db.timeout")(_.toInt)
} yield DbConfig(host, port, timeout)
}
I used identity for the host because it's already a string, so we don't need to transform it. Now, if you pass in a map with a missing key, you get a Left(MissingKey("db.host")). No crashes, just a value that tells you exactly what to fix in your application.conf.
📋 Practical Task
Exercise: Build a Service Gateway Configuration Loader
You are integrating with a third-party API and need to load its settings from a Map[String, String]. Your goal is to create a type-safe loader that prevents the application from starting with invalid settings.
- Requirements:
- Create a case class
ApiConfigwith three fields:apiKey(String),retryCount(Int), andisEnabled(Boolean). - Implement a sealed trait
ApiConfigErrorwith subtypes forMissingSettingandMalformedSetting. - Write a loader function
loadApiConfig(raw: Map[String, String]): Either[ApiConfigError, ApiConfig]. - Ensure that the
isEnabledfield is parsed correctly (hint:String.toBooleancan be used inside your transformation helper).
- Create a case class
- Test Cases to Handle:
- A map missing the
apiKeyshould returnLeft(MissingSetting("apiKey")). - A map where
retryCountis "abc" should returnLeft(MalformedSetting("retryCount", "abc")). - A map with all correct values should return
Right(ApiConfig(...)).
- A map missing the
There are no comments for now.