Flatten Scala Try

后端 未结 7 1023
天命终不由人
天命终不由人 2020-12-14 19:20

Is there a simple way to flatten a collection of try\'s to give either a success of the try values, or just the failure? For example:

def map(l:List[Int]) =          


        
7条回答
  •  自闭症患者
    2020-12-14 20:21

    Starting in Scala 2.13, most collections are provided with a partitionMap method which partitions elements based on a function returning either Right or Left.

    In our case we can call partitionMap with a function that transforms our Trys into Eithers (Try::toEither) in order to partition Successes as Rights and Failures as Lefts.

    Then it's just a matter of matching the resulting partitioned tuple of lefts and rights based on whether or not there are lefts:

    tries.partitionMap(_.toEither) match {
      case (Nil, rights)       => Success(rights)
      case (firstLeft :: _, _) => Failure(firstLeft)
    }
    // * val tries = List(Success(10), Success(20), Success(30))
    //       => Try[List[Int]] = Success(List(10, 20, 30))
    // * val tries = List(Success(10), Success(20), Failure(new Exception("error1")))
    //       => Try[List[Int]] = Failure(java.lang.Exception: error1)
    

    Details of the intermediate partitionMap step:

    List(Success(10), Success(20), Failure(new Exception("error1"))).partitionMap(_.toEither)
    // => (List[Throwable], List[Int]) = (List(java.lang.Exception: error1), List(10, 20))
    

提交回复
热议问题