PawelN
PawelN

Reputation: 848

Scala validation - Right-biased Either

At last Scala 2.12 has Right-biased Either. I heard it can be used for validation purpose but I cannot imagine this. I am not able to find good example.
Could somebody explain me how this monad could help me with validation? Also what other use-cases could be covered by this enhanced Either?

Upvotes: 1

Views: 1607

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149598

Either[A, B] be it right biased or not is great for validation/exception handling. Making it right biased makes it easier for us to compose operations over it.

Let's say we want to validate an object, what forms can a validation method take? The simplest form would be a predicate, a method taking an arbitrary object and returning a Bool:

sealed trait Base
case class Foo(I: Int)
case class Bar(s: String)

def isValid(b: Base): Bool = b match {
  case Foo(i) => i > 18
  case Bar(s) => s.length > 5
}

This will work, but may not be enough at times. What if this is a user facing API, and we want to be explicit about the possible errors with the received object such that the user will quickly understand what went wrong?

What if instead of returning a Bool, we'll either return a list of errors or return the valid object itself? This will allow us to further compose:

def validate(b: Base): Either[List[String], Base] = b match {
  case Foo(i) => if (i > 18) Right(b) else Left(List("i must be greater than 18"))
  case Bar(s) => if (s.length > 5) Right(b) else Left(List("s must be longer than 5 chars"))
}

Now we can map over it:

val foo = Foo(42)
val result = validate(foo).map { case Foo(i) => s"yay, valid foo number: $i" } 
result match {
  case Left(errors) => println(s"Something went wrong: ${errors.mkString(", ")}")
  case Right(msg) => println(msg)
}

We gain two things. First is the ability to compose validate with other operations and defer error handling, and the second is explicit errors. We could even take this further and make these errors typed, allowing the user to match on them and apply error handling for each use case, but that's for another time.

Upvotes: 5

Related Questions