-1

Suppose I have a List of tries in scala, for example: List(Try(a), Try(b), Try(c)). If want to write a code snippets that returns Success(List(a, b, c)) if all tries are successes, and returns a Failure if one of the tries is a failure.

The only way I found to do it is:

private def convertArrayOfSuccessesToSuccessOfByteArray(
      tryArrayForOutput: Array[Try[Byte]]
  ): Success[Array[Byte]] = {
    val outputArray = ArrayBuffer[Byte]()
    tryArrayForOutput.foreach(tryElem => {
      val Success(elem) = tryElem
      outputArray.append(elem)
    })
    Success(outputArray.toArray)
  }

As you can see, it's pretty cumbersome and not so "functional".

CrazySynthax
  • 13,662
  • 34
  • 99
  • 183

2 Answers2

1

Just get each value and wrap in a Try to catch the first error, if any

Try(tryArrayForOutput.map(_.get))
Tim
  • 26,753
  • 2
  • 16
  • 29
1

@Tim's answer is good in this case.

One more general functional way would be to fold and flatMap:

private def convertArrayOfSuccessesToSuccessOfByteArray(tryArrayForOutput: Seq[Try[Byte]]): Try[Seq[Byte]] = {
    tryArrayForOutput.foldLeft(Try(Seq[Byte]())) { (acc: Try[Seq[Byte]], t: Try[Byte]) =>
      acc.flatMap { seq: Seq[Byte] =>
        t.map((b: Byte) => seq :+ b)
      }
    }
  }

This can be generalised and is typically a method provided by libraries like Cats.

Gaël J
  • 11,274
  • 4
  • 17
  • 32