Options and Error Handling
Result Labels
Carry success or error as a labeled result.
result-labels
A result can be modeled as a success or error label with a value. This guards a risky step, like division, without an exception.
Result Labels
ResultLabels.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val divisor = 4
val ok = divisor != 0
val value = if (ok) 100 / divisor else 0
val outcome = if (ok) "ok:" + value else "error:divide-by-zero"
println("ok=" + ok)
println("outcome=" + outcome)
}
}
object Main {
def main(args: Array[String]): Unit = {
val divisor = 0
val ok = divisor != 0
val value = if (ok) 100 / divisor else 0
val outcome = if (ok) "ok:" + value else "error:divide-by-zero"
println("ok=" + ok)
println("outcome=" + outcome)
}
}
object Main {
def main(args: Array[String]): Unit = {
val divisor = 5
val ok = divisor != 0
val value = if (ok) 100 / divisor else 0
val outcome = if (ok) "ok:" + value else "error:divide-by-zero"
println("ok=" + ok)
println("outcome=" + outcome)
}
}
divisor ← 4, ok ← true, value ← 25, outcome ← ok:25
1object Main {2 def main(args: Array[String]): Unit = {3 val divisor→ 4 = 4 //@divisor=0, 54 val ok→ true = divisor4 != 05 val value→ 25 = if (oktrue) 100 / divisor4 else 06 val outcome→ ok:25 = if (oktrue) "ok:" + value25 else "error:divide-by-zero"78 println("ok=" + oktrue)9 println("outcome=" + outcomeok:25)10 }11}outputok=true outcome=ok:25
divisor ← 0, ok ← false, value ← 0, outcome ← error:divide-by-zero
1object Main {2 def main(args: Array[String]): Unit = {3 val divisor→ 0 = 04 val ok→ false = divisor0 != 05 val value→ 0 = if (okfalse) 100 / divisor0 else 06 val outcome→ error:divide-by-zero = if (okfalse) "ok:" + value0 else "error:divide-by-zero"78 println("ok=" + okfalse)9 println("outcome=" + outcomeerror:divide-by-zero)10 }11}outputok=false outcome=error:divide-by-zero
divisor ← 5, ok ← true, value ← 20, outcome ← ok:20
1object Main {2 def main(args: Array[String]): Unit = {3 val divisor→ 5 = 54 val ok→ true = divisor5 != 05 val value→ 20 = if (oktrue) 100 / divisor5 else 06 val outcome→ ok:20 = if (oktrue) "ok:" + value20 else "error:divide-by-zero"78 println("ok=" + oktrue)9 println("outcome=" + outcomeok:20)10 }11}outputok=true outcome=ok:20