【问题标题】:Future does not compile with Success and Failure未来不会与成功和失败一起编译
【发布时间】:2018-03-09 14:29:35
【问题描述】:

为什么这不能编译?我在Success 和Failure 行中收到以下错误:

构造函数不能被实例化为期望的类型;成立 : scala.util.Success[T] 需要:Int

还有代码:

    val future = Future { 1 }
    future.map { 
       case Success(s) => s
       case Failure(f) => 0
    }

【问题讨论】:

    标签: scala


    【解决方案1】:

    因为Future[Int] 中的map 需要一个域为Int 的函数,但您却试图将某个域为Try[Int] 的函数传递给它。

    句法上最接近的东西是onComplete:

    import scala.concurrent._
    import scala.concurrent.ExecutionContext.Implicits.global
    import scala.util.{Try, Success, Failure}
    
    val future = Future { 1 }
    future.onComplete { 
       case Success(s) => s
       case Failure(f) => 0
    }
    

    但是,这可能不是您想要的,因为表达式 s 和 0 不做任何事情,因此它们不是很有趣的回调。相反,您可能想要transform 结果:

    future.transform {
      case Success(s) => Success(s)
      case Failure(f) => Success(0)
    }
    

    或recover 来自失败的0:

    future.recover {
      case f: Exception => 0
    }
    

    【讨论】:

      【解决方案2】:

      您是否正在尝试执行以下操作:

       val future = Future {
            1
          }
          future onComplete  {
            case Success(s) => s
            case Failure(f) => 0
          }
      

      【讨论】:

        猜你喜欢
        • 2014-05-27
        • 2011-03-09
        • 2011-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-17
        • 1970-01-01
        • 2014-12-15
        相关资源
        最近更新 更多