Scala:理解中的非接触元素异常

Scala:理解中的非接触元素异常,scala,promise,future,for-comprehension,Scala,Promise,Future,For Comprehension,我有一个web请求的未来结果,我需要计算请求的大小。如果当前响应有项目,我需要发出另一个请求以获取下一个集合,等等。如果当前响应为空,我就完成了 我现在拥有的代码是: def list(prefix: String, lastItem: Option[String] = None, last: Seq[BucketItem] = Nil): Future[Iterable[BucketItem]] = { Logger.debug(s"list :: prefix=$prefix, las

我有一个web请求的未来结果,我需要计算请求的大小。如果当前响应有项目,我需要发出另一个请求以获取下一个集合,等等。如果当前响应为空,我就完成了

我现在拥有的代码是:

def list(prefix: String, lastItem: Option[String] = None, last: Seq[BucketItem] = Nil):  Future[Iterable[BucketItem]] = {
  Logger.debug(s"list :: prefix=$prefix, lastItem=$lastItem, lastItems=${last.size}")
  for {
    current <- s3.get(name, None, Some(prefix), delimiter, lastItem, None) map listResponse // type is Seq[BucketItem]
    next <- list(prefix, Some(current.last.name), last ++ current) if !(current.isEmpty)
  } yield last ++ current
}

我在这里使用理解的方法来轻松地处理收集期货的问题(至少我过去是这样做的)。有什么指导/需要阅读的东西吗?我是scala的新手,所以请温柔一点。

我认为您的过滤器放错地方了,这应该可以工作:

def list(prefix: String, lastItem: Option[String] = None, last: Seq[BucketItem] = Nil):  Future[Iterable[BucketItem]] = {
  Logger.debug(s"list :: prefix=$prefix, lastItem=$lastItem, lastItems=${last.size}")
  for {
    current <- s3.get(name, None, Some(prefix), delimiter, lastItem, None) map listResponse // type is Seq[BucketItem]
    if !current.isEmpty
    next <- list(prefix, Some(current.last.name), last ++ current)
  } yield last ++ current
}
def列表(前缀:String,lastItem:Option[String]=None,last:Seq[BucketItem]=Nil):Future[Iterable[BucketItem]={
Logger.debug(s“list::prefix=$prefix,lastItem=$lastItem,lastItems=${last.size}”)
为了{

当前您不使用变量
next
,因此无法获得
s3的结果。在第一次调用之后获取
调用。此外,您的
if!(current.isEmpty)
将对
Future
值调用
with filter
,这可能会产生失败的
Future
,这不是您想要的

下面是一个更简单的解决方案:

def list(prefix: String, lastItem: Option[String] = None, accum: Seq[BucketItem] = Vector()):  Future[Iterable[BucketItem]] = {
  s3.get(name, None, Some(prefix), delimiter, lastItem, None) flatMap { current =>
    if (current.isEmpty)
      Future.successful(accum)
    else
      list(prefix, bucketItems.last.name, accum ++ current)
  }
}
用于理解的A只能表示嵌套在
flatMap
调用内部的
map
(或
foreach
调用彼此内部),并使用filter
进行穿插调用。这里我们只需要对
flatMap
进行一次调用,因此
对于
没有任何用处


我还将
列表
替换为
向量
,它在结尾添加元素时性能更好。

这对我来说效果很好,我想我现在明白了原因。谢谢你的帮助。必须记住保持简单。有了这一点,我现在得到了一个谓词未实现异常,它来自未来。我认为被接受的回答(正确地)解释了失败的未来并不是我一开始真正想要的。谢谢你的帮助!
def list(prefix: String, lastItem: Option[String] = None, accum: Seq[BucketItem] = Vector()):  Future[Iterable[BucketItem]] = {
  s3.get(name, None, Some(prefix), delimiter, lastItem, None) flatMap { current =>
    if (current.isEmpty)
      Future.successful(accum)
    else
      list(prefix, bucketItems.last.name, accum ++ current)
  }
}