Skip to Content
Course content

19: Option, Either, and Try

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

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, and None otherwise.
  • Implement a function validateAmount(order: Order): Either[String, Order] that returns a Left("Too expensive") if the amount is over 1000.0, otherwise the Right(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)
Rating
0 0

There are no comments for now.

to be the first to leave a comment.