sábado, 11 de junio de 2022

Mónadas en Cats parte 11

cats.syntax.either también agrega algunos métodos útiles para instancias de Either

Los usuarios de Scala 2.11 o 2.12 pueden usar orElse y getOrElse para extraer valores del lado derecho o devolver un valor predeterminado:

import cats.syntax.either._

"Error".asLeft[Int].getOrElse(0)

// res11: Int = 0

"Error".asLeft[Int].orElse(2.asRight[String])

// res12: Either[String, Int] = Right(2)


El método de aseguramiento nos permite verificar si el valor de la derecha satisface un predicado:


-1.asRight[String].ensure("Must be non-negative!")(_ > 0)

// res13: Either[String, Int] = Left("Must be non-negative!")


Los métodos recover y recoverWith con proporcionan un manejo de errores similar al de sus homónimos en Future:


"error".asLeft[Int].recover {

case _: String => -1

}

// res14: Either[String, Int] = Right(-1)

"error".asLeft[Int].recoverWith {

case _: String => Right(-1)

}

// res15: Either[String, Int] = Right(-1)


Hay métodos leftMap y bimap para complementar el map:


"foo".asLeft[Int].leftMap(_.reverse)

// res16: Either[String, Int] = Left("oof")

6.asRight[String].bimap(_.reverse, _ * 7)

// res17: Either[String, Int] = Right(42)

"bar".asLeft[Int].bimap(_.reverse, _ * 7)

// res18: Either[String, Int] = Left("rab")


El método swap nos permite intercambiar izquierda por derecha:


123.asRight[String]

// res19: Either[String, Int] = Right(123)

123.asRight[String].swap

// res20: Either[Int, String] = Left(123)


Finalmente, Cats agrega una serie de métodos de conversión: toOption, toList, toTry, toValidated, etc.



No hay comentarios.:

Publicar un comentario