Átomo
30Et
Funcional e tipos · Scala

Either / Try

Abrir na tabela

Definição

Representam resultado ou erro sem exceções: Try captura exceções; Either carrega um erro descritivo.

Exemplos

1. Try
import scala.util.{Try, Success, Failure}

Try(spark.read.parquet(path)) match {
  case Success(df) => df.count()
  case Failure(e)  => println(s"read failed: ${e.getMessage}"); 0L
}
2. Either
def parseAmount(s: String): Either[String, BigDecimal] =
  Try(BigDecimal(s.replace(",", "."))).toOption.toRight(s"invalid amount: $s")
3. Separar sucessos de erros
val (errors, amounts) = raw.map(parseAmount).partitionMap(identity)

No mesmo grupo