Unable to use for comprehension to map over List within Future

后端 未结 4 788

I have this issue that I have to work around every time. I can\'t map over something that is contained within a Future using a for comprehension.

Example:

         


        
4条回答
  •  情书的邮戳
    2020-12-13 18:02

    Hmm, I think I got it. I need to wrap within a future as the for comprehension adds a flatmap.

    This works:

    for {
      list <- f
      e <- Future( list )
    } yield (e -> 1)
    

    When I added above I did not see any answers yet. However to expand on this it is possible to do work within one for-comprehension. Not sure if it is worth the Future overhead though (edit: by using successful there should be no overhead).

    for {
      list1 <- f
      list2 <- Future.successful( list1.map( _ -> 1) )
      list3 <- Future.successful( list2.filter( _._2 == 1 ) )
    } yield list3
    

    Addendum, half a year later.

    Another way to solve this is to simply use assignment = instead of <- when you have another type than the initial map return type.

    When using assignment that line does not get flat-mapped. You are now free to do an explicit map (or other transformation) that returns a different type.

    This is useful if you have several transformation where one step that does not have the same return type as the other steps, but you still want to use the for-comprehension syntax because it makes you code more readable.

    import scala.concurrent.ExecutionContext.Implicits.global
    import scala.concurrent.Future
    
    val f = Future( List("A", "B", "C") )
    def longRunning( l:List[(String, Int)] ) = Future.successful( l.map(_._2) )
    
    for {
      list <- f
      e = list.map( _ -> 1 )
      s <- longRunning( e )
    } yield s
    

提交回复
热议问题