Scala Future with filter in for comprehension

后端 未结 4 641
春和景丽
春和景丽 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:08

    This is a more idiomatic solution, in my opinion. This predicate function creates either a Future[Unit] or a failed future containing your exception. For your example, this would result in either a Success("Test1") or a Failure(Exception("Test2")). This is slightly different from "Test1" and "Test2", but I find this syntax to be more useful.

    def predicate(condition: Boolean)(fail: Exception): Future[Unit] = 
        if (condition) Future( () ) else Future.failed(fail)
    

    You use it like this:

    val f2 = for {
      i <- f1
      _ <- predicate( i == 2 )(new Exception("Test2"))
      j <- f3  // f3 will only run if the predicate is true
    } yield "Test1"
    

提交回复
热议问题