代码之家  ›  专栏  ›  技术社区  ›  Moha the almighty camel

scala:了解未来。恢复

  •  1
  • Moha the almighty camel  · 技术社区  · 7 年前

    我在玩 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 不工作。我用的不对吗?

    2 回复  |  直到 7 年前
        1
  •  3
  •   marstran    7 年前

    get Future ClassCastException

    def get(): Future[Int] = Future {
        throw new ClassCastException
    }
    
        2
  •  1
  •   pedrorijo91    7 年前

    Future.failed(new ClassCastException)
    

    def failed[T](exception: Throwable): scala.concurrent.Future[T]