How does Scala handle null safety, and what are the alternatives to using null?

Instruction: Discuss Scala's approach to null safety and the preferred alternatives to using null.

Context: This question tests the candidate's knowledge of Scala's type system and best practices for avoiding null pointer exceptions.

Updated

In Scala's default null mode, reference values can be null. Prefer an explicit absence type such as Option[A] for an optional result and convert nullable input at the boundary:

def displayName(nullable: String): String =
  Option(nullable).map(_.trim).filter(_.nonEmpty).getOrElse("Guest")

@main def nullExample(): Unit = {
  assert(displayName(null) == "Guest")
  assert(displayName("  ") == "Guest")
  assert(displayName(" Ada ") == "Ada")
  assert(Option(null).isEmpty)
  assert(Some(null).isDefined)
}

Option(value) maps a null value to None; Some(null) still contains null. Use matching, map, flatMap and deliberate fallbacks instead of an unchecked .get, which throws on None. An option can itself be null in the default mode, and its callbacks or nested fields may still fail. The type communicates absence; it does not force safe use. Use Either when callers need a reason for an expected failure rather than just presence or absence. Option behavior

Scala 3 also has opt-in explicit nulls via -Yexplicit-nulls: String and String | Null are distinguished, and checking a stable nullable value can narrow its type before use. This adds static checks but does not promise complete runtime null safety across unsafe casts, initialization or legacy boundaries. Avoid replacing deliberate checks with blanket .nn assertions. Explicit nulls

Related Questions