Describe the Option type in Scala.
Instruction: Explain what the Option type is and provide an example scenario where it's beneficial to use.
Updated
Option[A] represents either a present value, Some(value), or absence, None. It makes an optional result visible in the type, for example when a lookup finds no matching user.
final case class User(id: String, name: String)
@main def optionExample(): Unit = {
val users = Map("u1" -> User("u1", "Ava"))
def findUser(id: String): Option[User] = users.get(id)
def greeting(id: String): String =
findUser(id).map(u => s"Hello, ${u.name}").getOrElse("User not found")
assert(greeting("u1") == "Hello, Ava")
assert(greeting("missing") == "User not found")
val nullable: String = null
assert(Option(nullable) == None)
assert(Some(nullable).isDefined)
}
Option(value) converts a nullable boundary value to None when it is null. Some(null) still means a present null value. map, flatMap, pattern matching and deliberate fallbacks let callers consume the result without an unchecked .get. Option implementation and operations
The type does not force safe consumption: .get on None throws, and a callback can still throw or access a null field. Absence also does not explain why a lookup failed. Use a domain error type such as Either when callers need that distinction; keep service or database failures separate from a valid no-result outcome.
Related Questions
-
easy
-
medium
-
hard
-
hard
-
hard