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
19: Option, Either, and Try
I've seen this exact pattern in dozens of code reviews. A developer is building a user service, and they're using null to signal that a record wasn't found in the database. It looks fine during the happy-path testing, but then it hits production and the logs explode.
case class User(id: Int, name: String, email: String)
def findUserById(id: Int): User = {
val users = Map(1 -> User(1, "Alice", "alice@example.com"))
users.get(id).getOrElse(null) // Returning null for "not found"
}
val user = findUserById(2)
println(s"Found user: ${user.name}") // BOOM: NullPointerException
The danger of implicit absence
The problem here isn't just that the code crashed; it's that the type system lied to us. The signature findUserById(id: Int): User promises that you will get a User object back. It doesn't warn you that you might actually get null. You're forced to remember to write if (user != null) every single time you call this method. If you forget once, your app crashes. I hate writing null checks. They're noise, and they're fragile.
Modeling absence with Option
In Scala, we don't use null. We use Option. Think of Option as a box. Either the box contains a value (Some), or it's empty (None). This forces the caller to acknowledge the possibility of absence at compile time.
def findUserById(id: Int): Option[User] = {
val users = Map(1 -> User(1, "Alice", "alice@example.com"))
users.get(id) // Map.get already returns an Option!
}
val userOption = findUserById(2)
// Now the compiler won't let me just call .name.
// I have to handle both cases:
userOption match {
case Some(user) => println(s"Found user: ${user.name}")
case None => println("User not found.")
}
By changing the return type to Option[User], I've shifted the burden from the developer's memory to the compiler. You can't "forget" to handle the missing case anymore.
Providing context with Either
Option is great for "yes or no," but in real software, "no" isn't descriptive enough. Why did the user lookup fail? Was the ID invalid? Was the database down? Was the account suspended? This is where Either comes in.
Either[L, R] holds one of two values. By convention, the Right side holds the success value (because "right is right"), and the Left side holds the error.
sealed trait UserError
case object UserNotFound extends UserError
case object DatabaseTimeout extends UserError
def findUserDetailed(id: Int): Either[UserError, User] = {
if (id < 0) Left(UserNotFound)
else if (id == 99) Left(DatabaseTimeout)
else Right(User(id, "Alice", "alice@example.com"))
}
findUserDetailed(99) match {
case Right(user) => println(s"Welcome, ${user.name}")
case Left(UserNotFound) => println("Check your ID and try again.")
case Left(DatabaseTimeout) => println("Our servers are sweating. Try again in a minute.")
}
Taming exceptions with Try
Then there's the "wild west" of the JVM: exceptions. When you're calling a Java library or parsing a JSON string, the code might throw a RuntimeException. If you wrap that in a standard block, you're back to using try-catch blocks that clutter your logic. Try allows you to treat an exception as a value.
A Try[T] is either a Success(value) or a Failure(exception).
import scala.util.{Try, Success, Failure}
def parseUserId(input: String): Try[Int] = Try {
input.toInt // This throws NumberFormatException if input is "abc"
}
val result = parseUserId("not_a_number")
result match {
case Success(id) => println(s"Parsing worked: $id")
case Failure(e) => println(s"Parsing failed because: ${e.getMessage}")
}
I usually use Try at the very edges of my application—like where I read a file or call an API—and then immediately convert it into an Either to pass it into my business logic. It keeps the "scary" exception-throwing code isolated.
📋 Practical Task
Building a Resilient Order Processing Pipeline
You are tasked with creating a small pipeline that processes raw order strings. The pipeline needs to handle three potential points of failure: parsing the input, finding the user, and validating the order amount.
Requirements:
- Create a case class
Order(id: Int, userId: Int, amount: Double). - Implement a function
parseOrder(input: String): Try[Order]that splits a comma-separated string (e.g.,"101,1,49.99") into an Order object. - Implement a function
findUser(userId: Int): Option[String]that returns a username if the ID is 1 or 2, andNoneotherwise. - Implement a function
validateAmount(order: Order): Either[String, Order]that returns aLeft("Too expensive")if the amount is over 1000.0, otherwise theRight(order). - Create a "master" function
processOrder(input: String)that chains these together. If any step fails, it should return a descriptive error message.
Expected behavior:
"101,1,49.99"→ Success (User found, amount OK)"invalid_data"→ Failure (Parsing error)"102,5,20.00"→ Failure (User not found)"103,1,5000.00"→ Failure (Too expensive)
There are no comments for now.