簡體   English   中英

嵌套以理解期貨

[英]Nested For Comprehensions with Futures

鑒於:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def f: Future[Either[String, Int]] = Future { Right(100)}

def plus10(x: Int): Future[Either[String, Int]] = 
    Future { Right(x + 10) }

我正嘗試將Future[...]在一起:

scala> for { 
     |  x <- f
     |  y <- for { a <- x.right } yield plus10(a)
     | } yield y
<console>:17: error: value map is not a member of Product with 
    Serializable with 
   scala.util.Either[String,scala.concurrent.Future[Either[String,Int]]]
        y <- for { a <- x.right } yield plus10(a)
                     ^

我期望得到: Future{Right(100)}作為結果,但出現上述編譯時錯誤。

Travis Brown就如何使用Monad Transformers在這里修復我的代碼給出了一個很好的答案。 但是,如果沒有 Monad Transformers,我該如何解決我的代碼?

原來我可以使用Either#fold

 scala> for { 
     |  a <- f
     |  b <- a.fold(_ => Future { Left("bad") }, xx => plus10(xx) )
     | } yield b
res16: scala.concurrent.Future[Either[String,Int]] = 
     scala.concurrent.impl.Promise$DefaultPromise@67fc2aad

scala> res16.value
res17: Option[scala.util.Try[Either[String,Int]]] = 
          Some(Success(Right(110)))

當您的出現時,我正要回答,但您可能仍然會看一下:

val res = for {
  x <- f
  y <- x.fold(x => Future{Left(x)}, plus10)
} yield y

右側略顯簡潔,左側保留。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM