Option, Either and Try

A method that may find nothing, and a method that may fail, are ordinary results in Scala, not exceptions. Option[A] is a value that is there or is not, Either[E, A] is a value or an error with a reason, and Try[A] is a value or the exception that stopped the computation. All three are sealed hierarchies, so a match over them is checked like any other.

Option: a value or none

Map.get answers an Option, and the rest of the program works with the value without asking whether it is there. map and flatMap keep the absence, getOrElse and fold end it, and a for chains the steps that each may fail:

options.scala

case class User(id: Int, name: String) val users = Map(1 -> User(1, "Ada"), 2 -> User(2, "Grace")) def find(id: Int): Option[User] = users.get(id) def initial(name: String): Option[String] = name.headOption.map(_.toUpper.toString) @main def options(): Unit = println(find(1).map(_.name)) println(find(9).map(_.name)) println(find(9).getOrElse(User(0, "guest")).name) println(find(1).fold("none")(_.name)) println(find(9).isEmpty) val greeting = for user <- find(2) first <- initial(user.name) yield s"$first. ${user.name}" println(greeting) println(find(9).flatMap(user => initial(user.name)))

scala-cli run --server=false options.scala

Some(Ada)
None
guest
Ada
true
Some(G. Grace)
None

find(9).map(_.name) is None and not an exception, and every later step of the for is skipped once one step is empty. headOption is the same idea on a string: a character that may be missing is an Option[Char] instead of an index that can throw. Option.get is the one method that throws, and a program calls it only where it has already proved the value is there.

Either and Try: a value or a reason

Either[String, Int] says which side failed and why, which an Option cannot. Try wraps a computation that throws and turns the exception into a value, which is the bridge from the Java code of the standard library to the rest of a program:

either_and_try.scala

import scala.util.{Failure, Success, Try} def half(n: Int): Either[String, Int] = if n % 2 == 0 then Right(n / 2) else Left(s"$n is odd") def parse(text: String): Try[Int] = Try(text.toInt) @main def either_and_try(): Unit = println(half(10)) println(half(7)) println(half(10).map(_ * 2)) println(half(7).getOrElse(0)) val result = for a <- half(8) b <- half(a) yield b + 1 println(result) println(parse("42")) println(parse("4x").isFailure) println(parse("4x").recover { case _: NumberFormatException => -1 }) parse("7").foreach(n => println(n * 2)) parse("x") match case Success(n) => println(s"parsed $n") case Failure(e) => println(e.getClass.getSimpleName)

scala-cli run --server=false either_and_try.scala

Right(5)
Left(7 is odd)
Right(10)
0
Right(3)
Success(42)
true
Success(-1)
14
NumberFormatException

A for over an Either stops at the first Left, so half(8) reaches the second step and a Left would skip it. Try catches the exception toInt throws and hands back a Failure; recover replaces it with a value, and foreach runs only on success. The class name of the failure is printed rather than its message, because the message belongs to the JDK.

Related

Автор статьи: Arthur Isaev

Изображение баннера