在下面的示例中我得到了异常java.util.NoSuchElementException: Future.filter predicate is not satisfied
我想要结果Future( Test2 )
当检查if( i == 2 )
失败。如何在处理撰写 future 的 for 理解中处理过滤器/if?
下面是一个在 Scala REPL 中运行的简化示例。
Code:
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"
f2.recover{ case _ => "Test2" }
f2.value
在我看来,这是一个更惯用的解决方案。该谓词函数创建一个Future[Unit]
或者包含你的例外的失败的未来。对于您的示例,这将导致Success("Test1")
or a Failure(Exception("Test2"))
。这与“Test1”和“Test2”略有不同,但我发现这种语法更有用。
def predicate(condition: Boolean)(fail: Exception): Future[Unit] =
if (condition) Future( () ) else Future.failed(fail)
你像这样使用它:
val f2 = for {
i <- f1
_ <- predicate( i == 2 )(new Exception("Test2"))
j <- f3 // f3 will only run if the predicate is true
} yield "Test1"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)