What is Option in Scala and how does it replace null?
Answer
Option[T] is Scala's type-safe alternative to null references. It is a container with two subtypes: Some(value): contains a non-null value. None: represents the absence of a value. Instead of returning null (which causes NullPointerException), functions return Option: def findUser(id: Int): Option[User]. Working with Options: pattern match: opt match { case Some(v) => use(v); case None => default }. getOrElse: opt.getOrElse("default"). map: transform if present: opt.map(_.name). flatMap: chain optional operations. foreach: execute side effect if present. filter: convert Some to None if condition fails. Option makes the possibility of absence explicit in the type signature, forcing callers to handle both cases at compile time.
Previous
What is pattern matching in Scala?
Next
What is the difference between List and Array in Scala?