Using Eithers with Scala “for” syntax

前端 未结 3 829
盖世英雄少女心
盖世英雄少女心 2020-12-18 17:38

As I understand it, Scala \"for\" syntax is extremely similar to Haskell\'s monadic \"do\" syntax. In Scala, \"for\" syntax is often used for Lists and Op

3条回答
  •  既然无缘
    2020-12-18 18:17

    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.

提交回复
热议问题