The Option Type
An Option is a box that may hold a value or may be empty, and it warns you to check before using it. It helps avoid the crashes that come from using nothing.
In this page:
Syntax
val option: Option[Type] = Some(value)
val empty: Option[Type] = None
option.isDefined
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Returning
nullinstead ofNone, which brings back theNullPointerExceptionthatOptionavoids. - Wrapping a possibly-null value with
Some(x), whenOption(x)returnsNoneifxis null. - Calling
.getonNone, which throws; usegetOrElse,mapor pattern matching.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: