You really can use Seq[() => Either[Error, Item]] to defer calculations during collection creation. For example,
val doSomething1: () => Either[Error, Item] = () => { println(1); Right(1) } val doSomething2: () => Either[Error, Item] = () => { println(2); Right(2) } val doSomething3: () => Either[Error, Item] = () => { println(3); Left("error") } val doSomething4: () => Either[Error, Item] = () => { println(4); Right(3) } val doSomething5: () => Either[Error, Item] = () => { println(5); Left("second error") } val l = Seq(doSomething1, doSomething2, doSomething3, doSomething4, doSomething5)
( Item are Int in the example and Error are String s)
Then you can process them lazily stopping at the first crash using the following recursive function:
def processUntilFailure(l: Seq[() => Either[Error, Item]]): Either[Error, Seq[Item]] = { l.headOption.map(_.apply() match { case Left(error) => Left(error) case Right(item) => processUntilFailure(l.tail).right.map(_ :+ item) }).getOrElse(Right(Nil)) }
So now when I run processUntilFailure(l)
scala> processUntilFailure(l) 1 2 3 res1: Either[Error,Seq[Item]] = Left(error)
If you want to generate Either[Seq[String], Seq[Int]] (processing all operations). You can do this with a little change:
def processAll(l: Seq[() => Either[Error, Item]]): Either[Seq[Error], Seq[Item]] = { l.headOption.map(_.apply() match { case Left(error) => processAll(l.tail) match { case Right(_) => Left(Seq(error)) case Left(previousErrors) => Left(previousErrors :+ error) } case Right(item) => processAll(l.tail).right.map(_ :+ item) }).getOrElse(Right(Nil)) }
The only change you see is the left case matching the pattern. Doing this:
scala> processAll(l) 1 2 3 4 5 res0: Either[Seq[Error],Seq[Item]] = Left(List(second error, error))
processAll can be replaced by a common foldLeft with l
val zero: Either[Seq[Error], Seq[Item]] = Right(Seq[Item]()) l.foldLeft(zero) { (errorsOrItems: Either[Seq[Error], Seq[Item]], computation: () => Either[String, Int]) => computation.apply().fold( { (error: String) => Left(errorsOrItems.left.toOption.map(_ :+ error).getOrElse(Seq(error))) }, { (int: Int) => errorsOrItems.right.map(_ :+ int) }) }
processUntilFailure may, but not easily. Since interruption early from the fold is difficult. Here's a good answer about other possible approaches when you need to do this.