0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

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 exists
  • None when 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)
  }
}

All lessons in this course

  1. Avoiding null
  2. map and flatMap on Option
  3. getOrElse and fold
  4. Option in for-comprehensions
← Back to Scala for Backend Engineering & Functional Programming