Using Eithers with Scala “for” syntax

It doesn’t work in scala 2.11 and earlier because Either is not a monad. Though there’s talk of right-biasing it, you can’t use it in a for-comprehension: you have to get a LeftProject or RightProjection, like below:

for {
  foo <- Right[String,Int](1).right
  bar <- Left[String,Int]("nope").right
} yield (foo + bar)

That returns Left("nope"), by the way.

On Scalaz, you’d replace Either with Validation. Fun fact: Either‘s original author is Tony Morris, one of Scalaz authors. He wanted to make Either right-biased, but was convinced otherwise by a colleague.

Leave a Comment