I often use the function below to convert Option[Try[_]] to Try[Option[_]] , but it doesn't feel right. Can such functionality be expressed more idiomatically?
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 meanings:
val v1: Int = ??? val v2: Option[Int] = ???
I want to do an op operation (which may fail) on these values ββand pass this for the function f below.
def op(x: Int): Try[String] def f(x: String, y: Option[String]): Unit
I usually use readability for understanding:
for { opedV1 <- op(v1) opedV2 <- swap(v2.map(op)) } f(opedV1, opedV2)
PS. I would like to avoid some hard things like climbing.
source share