Options and Error Handling
Option Basics
Hold a value that may be missing with Option.
option-basics
An `Option[Int]` is either `Some(value)` or `None`. `isDefined` reports whether a value is present, and `getOrElse` supplies a fallback when it is missing.
Option Basics
OptionBasics.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val raw = 7
val maybe: Option[Int] = if (raw > 0) Some(raw) else None
val present = maybe.isDefined
val value = maybe.getOrElse(0)
println("present=" + present)
println("value=" + value)
}
}
object Main {
def main(args: Array[String]): Unit = {
val raw = -3
val maybe: Option[Int] = if (raw > 0) Some(raw) else None
val present = maybe.isDefined
val value = maybe.getOrElse(0)
println("present=" + present)
println("value=" + value)
}
}
object Main {
def main(args: Array[String]): Unit = {
val raw = 0
val maybe: Option[Int] = if (raw > 0) Some(raw) else None
val present = maybe.isDefined
val value = maybe.getOrElse(0)
println("present=" + present)
println("value=" + value)
}
}
raw ← 7, maybe ← Some(7), present ← true, maybe.isDefined ← true
1object Main {2 def main(args: Array[String]): Unit = {3 val raw→ 7 = 7 //@raw=0, -34 val maybe→ Some(7): Option[Int] = if (raw7 > 0) Some(raw) else None5 val present→ true = maybe.isDefined→ true6 val value→ 7 = maybeSome(7).getOrElse(0)78 println("present=" + presenttrue)9 println("value=" + value7)10 }11}outputpresent=true value=7
raw ← -3, maybe ← None, present ← false, maybe.isDefined ← false
1object Main {2 def main(args: Array[String]): Unit = {3 val raw→ -3 = -34 val maybe→ None: Option[Int] = if (raw-3 > 0) Some(raw) else None5 val present→ false = maybe.isDefined→ false6 val value→ 0 = maybeNone.getOrElse(0)78 println("present=" + presentfalse)9 println("value=" + value0)10 }11}outputpresent=false value=0
raw ← 0, maybe ← None, present ← false, maybe.isDefined ← false
1object Main {2 def main(args: Array[String]): Unit = {3 val raw→ 0 = 04 val maybe→ None: Option[Int] = if (raw0 > 0) Some(raw) else None5 val present→ false = maybe.isDefined→ false6 val value→ 0 = maybeNone.getOrElse(0)78 println("present=" + presentfalse)9 println("value=" + value0)10 }11}outputpresent=false value=0