Scala Future with filter in for comprehension

后端 未结 4 685
春和景丽
春和景丽 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条回答
  •  Happy的楠姐
    2021-02-04 01:21

    I liked @pkinsky 's idea, and made a bit of improvement. I dropped code to create Exception object like this:

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

    shouldTrue function is implemented using lihaoyi`s sourcecode library:

    def shouldTrue(condition: sourcecode.Text[Boolean])(implicit enclosing: sourcecode.Enclosing, file: sourcecode.File, line: sourcecode.Line): Future[Unit] =
      if (condition.value) Future.successful( () ) else Future.failed(new Exception(s"${condition.source} returns false\n\tat ${file.value}:${line.value}"))
    

    Then it automatically generates more meaningful exception message:

    java.lang.Exception: i == 2 returns false
        at \path\to\example.scala:17
    

提交回复
热议问题