Standard Library Utilities
Either Fallback
Represent success or a named error without throwing.
either
`Either[String, Int]` stores either an error label on the left or a useful value on the right. `getOrElse` supplies a fallback when the value is missing.
Either Fallback
EitherFallback.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val ok = true
val result: Either[String, Int] = if (ok) Right(42) else Left("missing")
val value = result.getOrElse(0)
val status = if (result.isRight) "ok" else "fallback"
println("status=" + status)
println("value=" + value)
}
}
object Main {
def main(args: Array[String]): Unit = {
val ok = false
val result: Either[String, Int] = if (ok) Right(42) else Left("missing")
val value = result.getOrElse(0)
val status = if (result.isRight) "ok" else "fallback"
println("status=" + status)
println("value=" + value)
}
}
ok ← true, result ← Right(42), value ← 42, status ← ok
1object Main {2 def main(args: Array[String]): Unit = {3 val ok→ true = true //@ok=false4 val result→ Right(42): Either[String, Int] = if (oktrue) Right(42) else Left("missing")5 val value→ 42 = resultRight(42).getOrElse(0)6 val status→ ok = if (result.isRighttrue) "ok" else "fallback"78 println("status=" + statusok)9 println("value=" + value42)10 }11}outputstatus=ok value=42
ok ← false, result ← Left(missing), value ← 0, status ← fallback
1object Main {2 def main(args: Array[String]): Unit = {3 val ok→ false = false4 val result→ Left(missing): Either[String, Int] = if (okfalse) Right(42) else Left("missing")5 val value→ 0 = resultLeft(missing).getOrElse(0)6 val status→ fallback = if (result.isRightfalse) "ok" else "fallback"78 println("status=" + statusfallback)9 println("value=" + value0)10 }11}outputstatus=fallback value=0