Scala用于理解未来和选项
我认为这一问题在中以及中都有涉及:monad不组合,因此您需要一个从一个monad到另一个monad的转换器,因为没有Scala用于理解未来和选项,scala,future,for-comprehension,scala-option,Scala,Future,For Comprehension,Scala Option,我认为这一问题在中以及中都有涉及:monad不组合,因此您需要一个从一个monad到另一个monad的转换器,因为没有flatMap操作可以将未来映射到选项 正如阿尔夫在回答中提到的,在本例中,您可以使用monad transformers 示例使用: 如果“组合的”未来的失败,你仍然可以使用fallbackTo,即使最好使用recover或recoverWith来实际检查你想从哪个可丢弃的中恢复。好吧,不要做任何像monad transformer之类的花哨事,我们可以简单地嵌套,以理解。它将
flatMap
操作可以将未来
映射到选项
正如阿尔夫在回答中提到的,在本例中,您可以使用monad transformers
示例使用:
如果“组合的”
未来的
失败,你仍然可以使用fallbackTo
,即使最好使用recover
或recoverWith
来实际检查你想从哪个可丢弃的
中恢复。好吧,不要做任何像monad transformer之类的花哨事,我们可以简单地嵌套,以理解。它将更加冗长,但没有额外的依赖关系
val combinedOT2: Future[Option[String]] =
(OptionT(file1) |@| OptionT(file2)).map(_ + " " + _).value
val res=(对于{
文件1opt
Error:(16, 11) type mismatch;
found : Option[String]
required: scala.concurrent.Future[?]
file1 <- file1Opt
^
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import cats.data.OptionT
import cats.implicits._
val file1: Future[Option[String]] = Future.successful(Some("file1"))
val file2: Future[Option[String]] = Future.successful(Some("file2"))
val combinedOT: OptionT[Future, String] =
for {
f1 <- OptionT(file1)
f2 <- OptionT(file2)
} yield s"$f1 $f2"
val combinedFO: Future[Option[String]] = combinedOT.value
val combinedF: Future[String] = combinedOT.getOrElse("Files not found")
val combinedOT2: Future[Option[String]] =
(OptionT(file1) |@| OptionT(file2)).map(_ + " " + _).value
val res = (for{
file1Opt <- f1
file2Opt <- f2
} yield for {
file1 <- file1Opt
file2 <- file2Opt
} yield combineFiles(file1, file2))
.fallbackTo(Future.successful(Some("Files not found")))
//or, alternatively, .fallbackTo(Future.successful(None))