How do you utilize 'for-comprehension' with Option to avoid null checks?
Instruction: Illustrate with code how 'for-comprehension' can be used with Option to handle nullable expressions.
Updated
Use Option for absence and sequence dependent lookups with for/yield. Convert a nullable value at the boundary with Option(value), which produces None for null. Do not construct Some(null) and expect it to mean absence.
This complete Scala 3 example uses real in-memory lookup failures rather than unconditional successful stubs:
final case class User(id: Int, name: String)
final case class Address(street: String)
@main def optionLookupExample(): Unit = {
val users = Map(1 -> User(1, "Ava"), 2 -> User(2, "Bo"))
val addresses = Map(1 -> Address("123 Scala Lane"))
var addressCalls = 0
def findAddress(id: Int): Option[Address] = {
addressCalls += 1
addresses.get(id)
}
def streetFor(rawId: String): Option[String] = for {
text <- Option(rawId)
id <- text.toIntOption
user <- users.get(id)
address <- findAddress(user.id)
} yield address.street
assert(streetFor("1") == Some("123 Scala Lane"))
assert(streetFor("2") == None)
assert(addressCalls == 2)
assert(streetFor("99") == None)
assert(streetFor("invalid") == None)
assert(streetFor(null) == None)
assert(addressCalls == 2)
}
The successful path yields the street. If an earlier generator is None, later dependent lookups are skipped; a missing address also yields None. The comprehension composes flatMap and a final map, rather than catching exceptions. Option operations
Every missing case intentionally has the same result here. Use Either with domain errors if callers must distinguish invalid input, unknown user and missing address. A thrown database exception, null inside an object's fields, or a function returning null instead of Option still needs separate handling. Do not call .get on an unchecked option; consume it through matching, mapping or a deliberate fallback.