Combining List, Future and Option in for-comprehension - scalaz

前端 未结 2 548
-上瘾入骨i
-上瘾入骨i 2021-01-20 18:33

I\'ve got following problem:

val sth: Future[Seq[T, S]] = for {
  x <- whatever: Future[List[T]]
  y <- x: List[T]
  z <- f(y): Future[Option[S]]
           


        
2条回答
  •  佛祖请我去吃肉
    2021-01-20 18:57

    You could do something like what you need using the scalaz ListT monad transformer

     object Test {
       import scalaz._
       import ListT._
       type T = String
       type S = Int
       val whatever: Future[List[T]] = ??? // you get this somewhere
       def f(y: T): Future[Option[S]] = ??? // function that returns future of option
    
       val sth: Future[List[(T, S)]] = (for {
         y <- listT(whatever) 
         // you cannot mix list and option, but you can convert the option to a list of 1 item
         n <- listT(f(y).map(_.toList)) 
       } yield y -> n).run
     }
    

    N.B.: Since you start with a future, you cannot return a Seq[(T,S)], you can only have a future. You have to call Await.result if you want to block and get the result.

提交回复
热议问题