Scala Future with filter in for comprehension

后端 未结 4 647
春和景丽
春和景丽 2021-02-04 00:45

In the example below I get the exception java.util.NoSuchElementException: Future.filter predicate is not satisfied

I want to have the result Future(

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-04 01:05

    Of course I figured out one solution myself. Perhaps there are better, more idiomatic, solutions?

    import scala.concurrent.Future
    import scala.util.{ Try, Success, Failure }
    import scala.concurrent.ExecutionContext.Implicits.global
    
    val f1 = Future( 1 )
    val f2 = for {
      i <- f1
      if( i == 2 )
    } yield "Test1"
    val f3 = f2.recover{ case _ => "Test2"  }
    // OR val f3 = f2.fallbackTo( Future( "Test2" ) )
    f3.value
    

提交回复
热议问题