Search code examples
scalaoption-typetraversable

How to convert Option[Try[_]] to Try[Option[_]]?


I quite often use the function below to convert Option[Try[_]] to Try[Option[_]] but it feels wrong. Can be such a functionality expressed in more idiomatic way?

def swap[T](optTry: Option[Try[T]]): Try[Option[T]] = {
  optTry match {
    case Some(Success(t)) => Success(Some(t))
    case Some(Failure(e)) => Failure(e)
    case None => Success(None)
  }
}

Say I have two values:

val v1: Int = ???
val v2: Option[Int] = ???

I want to make an operation op (which can fail) on these values and pass that to function f below.

def op(x: Int): Try[String]
def f(x: String, y: Option[String]): Unit

I typically use for comprehension for readability:

for {
  opedV1 <- op(v1)
  opedV2 <- swap(v2.map(op))
} f(opedV1, opedV2)

PS. I'd like to avoid some heavy stuff like scalaz.


Solution

  • Sounds like Try { option.map(_.get) } will do what you want.