Scala未来与过滤器在理解 [英] Scala Future with filter in for comprehension

查看:247
本文介绍了Scala未来与过滤器在理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的例子中,我得到了异常 java.util.NoSuchElementException:Future.filter谓词不满足



当检查 if(i == 2)失败时,我希望得到结果 Future(Test2)如何处理过滤器/如果在处理组合期货的理解?



下面是一个在Scala REPL中工作的简单示例。



代码:

  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)
} yieldTest1
f2.recover {case _ => Test2}
f2.value


解决方案

for-comprehension 中,您按照 i == 2 过滤。因为 f1 的值不是两个,所以不会产生成功,而是一个失败。过滤器的谓词不满足,因为你的错误信息告诉你。但是, f2.recover 会返回一个新的 Future f2 的值不被操纵。它仍然存储失败。这就是当您调用 f2.value 时出现错误消息的原因。


我能想到的唯一选择就是在 for-comprehension中使用 else 如图所示此处。 (i < - f1)yield {b $ b $ if(i == 2)Test1
elseTest2
}
f2.value

将会返回 Some(成功(Test2))作为您的 f3.value


In the example below I get the exception java.util.NoSuchElementException: Future.filter predicate is not satisfied

I want to have the result Future( Test2 ) when the check if( i == 2 ) fails. How do I handle filter/if within a for comprehension that deals with composing futures?

Below is a simplified example that works in the 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

解决方案

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.

这篇关于Scala未来与过滤器在理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆