Scala过滤器对布尔内部的未来进行理解
我试图验证项目序列的未来。我的validate方法还返回布尔值的未来。我能够让它工作,但我不确定我自己是否理解这里发生了什么 所以,我有一个有效的代码和一个无效的代码。有人知道这里发生了什么吗? 还有,如何通过在地图后链接过滤器使其工作,以便其全部位于一个位置,而不必在以后使用分配Scala过滤器对布尔内部的未来进行理解,scala,future,scala-collections,for-comprehension,Scala,Future,Scala Collections,For Comprehension,我试图验证项目序列的未来。我的validate方法还返回布尔值的未来。我能够让它工作,但我不确定我自己是否理解这里发生了什么 所以,我有一个有效的代码和一个无效的代码。有人知道这里发生了什么吗? 还有,如何通过在地图后链接过滤器使其工作,以便其全部位于一个位置,而不必在以后使用分配 def main(args: Array[String]): Unit = { println(Await.result(testMethod(), Duration.Inf)) } def validati
def main(args: Array[String]): Unit = {
println(Await.result(testMethod(), Duration.Inf))
}
def validationMethod(n: Int) = {
Future { n % 2 == 0 }
}
有效的代码:
def testMethod() = {
for {
seqOfIntegers <- Future { List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) }
numberToBooleanTupleSeq <- Future.sequence(seqOfIntegers.map {
number =>
validationMethod(number)
.map(validtedBooleanTuple => (number, validtedBooleanTuple))
})
finalIntegerSeq = numberToBooleanTupleSeq.filter(_._2).map(_._1)
} yield {
finalIntegerSeq
}
def testMethod()={
为了{
SeqOfInteger(数字,有效布尔元组))
})
finalIntegerSeq=numberToBooleanTupleSeq.filter(u._2).map(u._1)
}屈服{
finalIntegerSeq
}
不起作用的代码:
def testMethod() = {
for {
seqOfIntegers <- Future { List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) }
finalIntegerSeq <- Future.sequence(seqOfIntegers.map {
number =>
validationMethod(number)
.map(validtedBooleanTuple => (number, validtedBooleanTuple))
.filter(_._2)
.map(_._1)
})
} yield {
finalIntegerSeq
}
}
def testMethod()={
为了{
SeqOfInteger(数字,有效布尔元组))
.filter(uu.u 2)
.map(u.u 1)
})
}屈服{
finalIntegerSeq
}
}
按照类型进行操作。在第二个代码段中,您正在调用
过滤器
,调用的是一个未来,但它并没有像您预期的那样工作。因为,它不会从futures集合中删除该元素,而是返回一个失败的Future,并带有一个NoSuchElementException
,这会使所有代码都因该异常而失败
顺便说一句,这里是一个抛光版本的工作代码,这是一个有点更有效和可读性
import scala.concurrent.Future
def validationMethod(n: Int): Future[Boolean] =
Future((n % 2) == 0)
def testMethod() =
for {
seqOfIntegers <- Future {
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
}
validated <- Future.traverse(seqOfIntegers) { number =>
validationMethod(number).map { boolean =>
number -> boolean
}
}
result = validated.collect {
case (n, true) => n
}
} yield result
导入scala.concurrent.Future
def validationMethod(n:Int):未来[布尔]=
未来((n%2)==0)
def testMethod()=
为了{
Seqof积分
数字->布尔值
}
}
结果=已验证。收集{
案例(n,真)=>n
}
}产量结果