Avoiding null
Option basics.
The Problem With null
In many languages, a missing value is represented by null. But null causes the dreaded NullPointerException when you forget to check it.
Scala offers a safer alternative: the Option type.
What Is Option?
Option[A] represents a value that may or may not be present. It has exactly two cases:
Some(value)when a value existsNonewhen there is no value
The type itself tells you a value might be missing.
object Main {
def main(args: Array[String]): Unit = {
val present: Option[Int] = Some(42)
val absent: Option[Int] = None
println(present)
println(absent)
}
}