typestar

Either para validar en Scala

Either guarda el motivo del rechazo de un valor, donde un Option pelado no puede.

// Either carries a failure on the Left and a success on the Right,
// so the reason for a rejection survives the return trip.
case class Booking(guest: String, nights: Int)

def validate(guest: String, nights: Int): Either[String, Booking] =
  if guest.isEmpty then Left("guest name is required")
  else if nights < 1 then Left(s"$nights nights is not a stay")
  else if nights > 30 then Left("stays over 30 nights need approval")
  else Right(Booking(guest, nights))

// Matching both sides means no failure can be quietly dropped.
def confirm(guest: String, nights: Int): String =
  validate(guest, nights) match
    case Right(booking) => s"booked ${booking.guest} for ${booking.nights}"
    case Left(problem)  => s"rejected: $problem"

// map and getOrElse act on the Right side and leave a Left untouched.
def nightsOrZero(guest: String, nights: Int): Int =
  validate(guest, nights).map(_.nights).getOrElse(0)

Cómo funciona

  1. validate devuelve un Left con el mensaje, o Right(Booking(guest, nights)) cuando pasan todas las reglas.
  2. El match nombra ambos lados, case Right(booking) y case Left(problem), así no se pierde ninguna falla.
  3. validate(guest, nights).map(_.nights) actúa solo sobre el lado Right y deja intacto el Left.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
19
Caracteres a escribir
897
Tokens
162
Ritmo de tres estrellas
70 tpm

Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 139 segundos.

Escribe este fragmento

Paso 3 de 3 en Option y Either; paso 21 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →