Avoiding null
Option basics.
Avoiding null is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)
}
}Creating Some
Wrap an existing value in Some to say it is definitely present.
object Main {
def main(args: Array[String]): Unit = {
val name: Option[String] = Some("Ada")
println(name)
}
}Representing Absence With None
None is the single value used when nothing is there. It works for any Option type.
object Main {
def lookup(found: Boolean): Option[Int] =
if (found) Some(100) else None
def main(args: Array[String]): Unit = {
println(lookup(true))
println(lookup(false))
}
}Functions That May Fail
Returning Option makes the possibility of no result explicit in the type signature. Callers cannot ignore it.
object Main {
def findUser(id: Int): Option[String] =
if (id == 1) Some("Grace") else None
def main(args: Array[String]): Unit = {
println(findUser(1))
println(findUser(2))
}
}Checking With isDefined and isEmpty
isDefined tells you if an Option is a Some, and isEmpty tells you if it is None.
object Main {
def main(args: Array[String]): Unit = {
val a: Option[Int] = Some(5)
val b: Option[Int] = None
println(a.isDefined)
println(b.isEmpty)
}
}Pattern Matching an Option
Because Option is a sealed ADT, you can pattern match on it. This handles both presence and absence clearly.
object Main {
def greet(name: Option[String]): String = name match {
case Some(n) => s"Hello, $n"
case None => "Hello, stranger"
}
def main(args: Array[String]): Unit = {
println(greet(Some("Bo")))
println(greet(None))
}
}Option From Nullable Values
If you must work with code that returns null, wrap it with Option(...). It converts null to None and any real value to Some.
object Main {
def main(args: Array[String]): Unit = {
val maybe = Option("data")
val nothing = Option(null)
println(maybe)
println(nothing)
}
}Standard Library Returns Option
Many built-in methods already return Option instead of risking errors. For example, List.headOption safely handles empty lists.
object Main {
def main(args: Array[String]): Unit = {
val xs = List(1, 2, 3)
val empty = List.empty[Int]
println(xs.headOption)
println(empty.headOption)
}
}Why Option Over null?
Option beats null because it:
- Makes missing values visible in the type
- Forces callers to handle the absent case
- Eliminates NullPointerExceptions
- Composes with map, flatMap, and for-comprehensions
Putting It Together
A small lookup that returns Option, then is safely handled with pattern matching.
object Main {
val prices = Map("apple" -> 3, "pear" -> 5)
def priceOf(item: String): Option[Int] = prices.get(item)
def main(args: Array[String]): Unit = {
priceOf("apple") match {
case Some(p) => println(s"costs $p")
case None => println("not for sale")
}
println(priceOf("banana"))
}
}Quick Check
Test your understanding of Option.
Recap
You learned to avoid null with Option:
Option[A]isSome(value)orNone- It makes possible absence explicit in the type
- Check with
isDefined/isEmptyor pattern match - Use
Option(x)to wrap nullable values - Library methods like
headOptionandMap.getreturn Option
Frequently asked questions
Is the “Avoiding null” lesson free?
Yes — the full text of “Avoiding null” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.
What will I learn in “Avoiding null”?
Option basics. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Scala for Backend Engineering & Functional Programming?
No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Avoiding null” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?
Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.