What's the deal with all the Either cruft?

前端 未结 4 1835
Happy的楠姐
Happy的楠姐 2020-12-23 14:04

The Either class seems useful and the ways of using it are pretty obvious. But then I look at the API documentation and I\'m baffled:

def joinLeft [A1 >:          


        
4条回答
  •  情书的邮戳
    2020-12-23 14:31

    joinLeft and joinRight enable you to "flatten" a nested Either:

    scala> val e: Either[Either[String, Int], Int] = Left(Left("foo"))
    e: Either[Either[String,Int],Int] = Left(Left(foo))
    
    scala> e.joinLeft
    res2: Either[String,Int] = Left(foo)
    

    Edit: My answer to this question shows one example of how you can use the projections, in this case to fold together a sequence of Eithers without pattern matching or calling isLeft or isRight. If you're familiar with how to use Option without matching or calling isDefined, it's analagous.


    While curiously looking at the current source of Either, I saw that joinLeft and joinRight are implemented with pattern matching. However, I stumbled across this older version of the source and saw that it used to implement the join methods using projections:

    def joinLeft[A, B](es: Either[Either[A, B], B]) =
      es.left.flatMap(x => x)
    

提交回复
热议问题