Future[Option] in Scala for-comprehensions

前端 未结 5 1658
闹比i
闹比i 2020-12-07 19:16

I have two functions which return Futures. I\'m trying to feed a modified result from first function into the other using a for-yield comprehension.

This approach w

5条回答
  •  离开以前
    2020-12-07 19:45

    What behavior would you like to occur in the case that the Option[School] is None? Would you like the Future to fail? With what kind of exception? Would you like it to never complete? (That sounds like a bad idea).

    Anyways, the if clause in a for-expression desugars to a call to the filter method. The contract on Future#filteris thus:

    If the current future contains a value which satisfies the predicate, the new future will also hold that value. Otherwise, the resulting future will fail with a NoSuchElementException.

    But wait:

    scala> None.get
    java.util.NoSuchElementException: None.get
    

    As you can see, None.get returns the exact same thing.

    Thus, getting rid of the if sid.isDefined should work, and this should return a reasonable result:

      val schoolFuture = for {
        ud <- userStore.getUserDetails(user.userId)
        sid = ud.right.toOption.flatMap(_.schoolId)
        s <- schoolStore.getSchool(sid.get)
      } yield s
    

    Keep in mind that the result of schoolFuture can be in instance of scala.util.Failure[NoSuchElementException]. But you haven't described what other behavior you'd like.

提交回复
热议问题