The Option Type
In this page:
The Option Type
Option[T] represents a value that might or might not be present, replacing the need for null to signal absence. It's a container holding either exactly one value or none at all, forcing callers to explicitly handle the "missing" case rather than risking a null-pointer error. Methods that might not find a result, like a map lookup, conventionally return an Option instead of null.
Note: Prefer Option over null for any value that might legitimately be absent -- it makes the possibility of absence visible in the type itself.
Example: The Option Type
object Main extends App {
val found: Option[Int] = Some(42)
val missing: Option[Int] = None
println(found)
println(missing)
println(found.isDefined)
println(missing.isEmpty)
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: