怎么把Option [Try [_]]转换为Try [Option [_]]? [英] How to convert Option[Try[_]] to Try[Option[_]]?
本文介绍了怎么把Option [Try [_]]转换为Try [Option [_]]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常使用下面的函数将Option[Try[_]]
转换为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)
}
}
说我有两个值:
val v1: Int = ???
val v2: Option[Int] = ???
我想对这些值进行操作op
(这可能会失败),并将其传递给下面的函数f
.
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.我想避免使用像scalaz这样的笨重的东西.
PS. I'd like to avoid some heavy stuff like scalaz.
推荐答案
像Try { option.map(_.get) }
这样的声音将满足您的要求.
Sounds like Try { option.map(_.get) }
will do what you want.
这篇关于怎么把Option [Try [_]]转换为Try [Option [_]]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文