Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala用于理解未来和选项_Scala_Future_For Comprehension_Scala Option - Fatal编程技术网

Scala用于理解未来和选项

Scala用于理解未来和选项,scala,future,for-comprehension,scala-option,Scala,Future,For Comprehension,Scala Option,我认为这一问题在中以及中都有涉及:monad不组合,因此您需要一个从一个monad到另一个monad的转换器,因为没有flatMap操作可以将未来映射到选项 正如阿尔夫在回答中提到的,在本例中,您可以使用monad transformers 示例使用: 如果“组合的”未来的失败,你仍然可以使用fallbackTo,即使最好使用recover或recoverWith来实际检查你想从哪个可丢弃的中恢复。好吧,不要做任何像monad transformer之类的花哨事,我们可以简单地嵌套,以理解。它将

我认为这一问题在中以及中都有涉及:monad不组合,因此您需要一个从一个monad到另一个monad的转换器,因为没有
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))