我正在尝试使用Future.recover (通过intelJ中的scala表单,如果它有任何重要性的话)
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def get():Future[Int] = {
throw new ClassCastException
}
val n = get().map{
x => x + 1
}.recover{
case e: Throwable => print("we recovered")
0
}
n.map(print(_)) // not getting here我原以为0会被打印出来。然而,这是我得到的:
java.lang.ClassCastException
at #worksheet#.get(test.sc:5)
at #worksheet#.n$lzycompute(test.sc:8)
at #worksheet#.n(test.sc:8)
at #worksheet#.get$$instance$$n(test.sc:8)
at A$A76$.main(test.sc:32)
at #worksheet#.#worksheet#(test.sc)为什么我的recover不工作。我是不是用错了?
发布于 2018-07-27 20:24:36
您的get函数没有返回Future。它会立即抛出ClassCastException。您需要在某个位置创建Future。
将您的get函数更改为:
def get(): Future[Int] = Future {
throw new ClassCastException
}发布于 2018-07-28 18:36:37
你可能想要这样的东西:
Future.failed(new ClassCastException)签名是:
def failed[T](exception: Throwable): scala.concurrent.Future[T]https://stackoverflow.com/questions/51557846
复制相似问题