Scala:理解 Future.recover

Moh*_*mel 2 scala future

我正在玩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
Run Code Online (Sandbox Code Playgroud)

我期待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)
Run Code Online (Sandbox Code Playgroud)

为什么我的recover不工作。我使用它不正确吗?

mar*_*ran 6

您的get函数不会返回Future. 它只是立即抛出ClassCastException. 您需要创建Future某个地方。

将您的get功能更改为:

def get(): Future[Int] = Future {
    throw new ClassCastException
}
Run Code Online (Sandbox Code Playgroud)