kop*_*zko 7 scala optional traversable
我经常使用下面的函数转换Option[Try[_]]为Try[Option[_]]但感觉不对.可以用更惯用的方式表达这样的功能吗?
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)
}
}
Run Code Online (Sandbox Code Playgroud)
说我有两个值:
val v1: Int = ???
val v2: Option[Int] = ???
Run Code Online (Sandbox Code Playgroud)
我想op对这些值进行操作(可能会失败)并将其传递给f下面的函数.
def op(x: Int): Try[String]
def f(x: String, y: Option[String]): Unit
Run Code Online (Sandbox Code Playgroud)
我通常用于理解可读性:
for {
opedV1 <- op(v1)
opedV2 <- swap(v2.map(op))
} f(opedV1, opedV2)
Run Code Online (Sandbox Code Playgroud)
PS.我想避免像scalaz这样沉重的东西.
该猫库允许你排序的Option一个Try非常容易:
scala> import cats.implicits._
import cats.implicits._
scala> import scala.util.{Failure, Success, Try}
import scala.util.{Failure, Success, Try}
scala> Option(Success(1)).sequence[Try, Int]
res0: scala.util.Try[Option[Int]] = Success(Some(1))
scala> Option(Failure[Int](new IllegalArgumentException("nonpositive integer"))).sequence[Try, Int]
res1: scala.util.Try[Option[Int]] = Failure(java.lang.IllegalArgumentException: nonpositive integer)
scala> None.sequence[Try, Int]
res2: scala.util.Try[Option[Int]] = Success(None)
Run Code Online (Sandbox Code Playgroud)
听起来像是Try { option.map(_.get) }会做你想做的事。