Scala:理解 Future.recover
Scala : Understanding Future.recover
我正在玩 Future.recover
(通过 intelJ 中的 scala sheet 如果它有任何重要性的话)
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
不工作。我是不是用错了?
您的 get
函数没有 return Future
。它只是立即抛出 ClassCastException
。您需要在某处创建 Future
。
将您的 get
函数更改为:
def get(): Future[Int] = Future {
throw new ClassCastException
}
你可能想要这样的东西:
Future.failed(new ClassCastException)
签名是:
def failed[T](exception: Throwable): scala.concurrent.Future[T]
我正在玩 Future.recover
(通过 intelJ 中的 scala sheet 如果它有任何重要性的话)
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
不工作。我是不是用错了?
您的 get
函数没有 return Future
。它只是立即抛出 ClassCastException
。您需要在某处创建 Future
。
将您的 get
函数更改为:
def get(): Future[Int] = Future {
throw new ClassCastException
}
你可能想要这样的东西:
Future.failed(new ClassCastException)
签名是:
def failed[T](exception: Throwable): scala.concurrent.Future[T]