Lesson 13 of 15
Options
Options
Scala's Option[T] represents a value that may or may not exist — it's either Some(value) or None:
def safeDivide(a: Int, b: Int): Option[Int] =
if (b == 0) None else Some(a / b)
println(safeDivide(10, 2)) // Some(5)
println(safeDivide(10, 0)) // None
getOrElse
Provide a default value with getOrElse:
val result = safeDivide(10, 0).getOrElse(-1)
println(result) // -1
Your Task
Write a function safeHead that takes a List[Int] and returns Some(first) if the list is non-empty, or None if it's empty.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.