Using Eithers with Scala “for” syntax

前端 未结 3 836
盖世英雄少女心
盖世英雄少女心 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:21

    As of Scala 2.12, Either is now right biased

    From the documentation:

    As Either defines the methods map and flatMap, it can also be used in for comprehensions:

    val right1: Right[Double, Int] = Right(1)
    val right2                     = Right(2)
    val right3                     = Right(3)
    val left23: Left[Double, Int]  = Left(23.0)
    val left42                     = Left(42.0)
    
    for (
      a <- right1;
      b <- right2;
      c <- right3
    ) yield a + b + c // Right(6)
    
    for (
      a <- right1;
      b <- right2;
      c <- left23
    ) yield a + b + c // Left(23.0)
    
    for (
      a <- right1;
      b <- left23;
      c <- right2
    ) yield a + b + c // Left(23.0)
    
    // It is advisable to provide the type of the “missing” value (especially the right value for `Left`)
    // as otherwise that type might be infered as `Nothing` without context:
    for (
      a <- left23;
      b <- right1;
      c <- left42  // type at this position: Either[Double, Nothing]
    ) yield a + b + c
    //            ^
    // error: ambiguous reference to overloaded definition,
    // both method + in class Int of type (x: Char)Int
    // and  method + in class Int of type (x: Byte)Int
    // match argument types (Nothing)
    

提交回复
热议问题