"实现限制:值类中不允许嵌套类计划在后续版本中删除此限制."

use*_*315 7 scala

方法描述:

给出一个期货清单fs,返回未来持有所有期货的价值清单fs.只有在所有期货完成后,返回的未来才会fs完成.列表中的值与相应的期货的顺序相同fs.如果任何期货fs失败,由此产生的未来也会失败.

这就是我做的:

implicit class FutureCompanionOps[T](val f: Future.type) extends AnyVal {
    /***

    //Some others method

    ***/
    def all[T](fs: List[Future[T]]): Future[List[T]] = async {
      var fsVar = fs;
      val l = List()     
      while(fsVar.nonEmpty){
        await{fsVar.head} :: l
        fsVar = fsVar.tail
      }
      l
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我在这一行得到以下编译错误def all[T](fs: List[Future[T]]): Future[List[T]] = async {:

实现限制:值类中不允许嵌套类计划在后续版本中删除此限制.

有人可以解释我这个错误并告诉我一个解决方法吗?

Oli*_*ain 5

来自FAQ:

Scala异步功能即将发布,并且部分是实验性的.

作为在值类中使用Scala Async的解决方法,请考虑使用以下技巧将异步调用移到值类之外:

class FutureOps[T](f: Future[T]) extends AnyVal {
  def foo: Future[T] = fooImpl(f)
}

def fooImpl(f: Future[T]) = async {
  val x = await { f }
  throw new Exception
}
Run Code Online (Sandbox Code Playgroud)

如果或其他代码杂耍和重构不能解决问题,可以考虑使用常规的功能组合程序一样 map, flatMap, continueWith 和他们朋友的休息.


小智 5

可以通过将该方法移到值类(FutureCompanionOps)之外来解决此特定问题.

def allOutside[T](fs: List[Future[T]]): Future[List[T]] = async {
    var fsVar = fs;
    val l = Nil      
    while(fsVar.nonEmpty){
        await{fsVar.head} :: l
        fsVar = fsVar.tail
    }
    l.toList
}

implicit class FutureCompanionOps[T](val f: Future.type) extends AnyVal {
    /***

    //Some others method
***/
    def all[T](fs: List[Future[T]]): Future[List[T]] = allOutside(fs)
}
Run Code Online (Sandbox Code Playgroud)

即使是课程页面上常见问题解答也没有提供有关此处发生的事情的进一步说明,只是该功能是实验性的.异步{}导致宏变得难以跟踪,因此......可能在某行的某个位置创建了一个嵌套类,根据本文不允许在值类中使用.

建议您至今不要使用async {}并等待{}.

Nb你的代码不起作用,但我不应该破坏乐趣,因为问题不是那个