Scala Future with filter in for comprehension

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

    In your for-comprehension, you are filtering by i == 2. Because the value of f1 is not two, it will not yield a Success but instead a Failure. The predicate of the filter is not satisfied, as your errror message tells you. However, f2.recover returns a new Future. The value of f2 is not manipulated. It still stores the Failure. That is the reason you get the error message when you call f2.value.

    The only alternative I can think of would be using an else in your for-comprehension as shown here.

    val f2 = for ( i <- f1) yield {
      if (i == 2) "Test1"
      else "Test2"
    }
    f2.value
    

    This will return Some(Success(Test2)) as your f3.value does.

提交回复
热议问题