future.recover 在 Play for Scala 中无法编译

future.recover in Play for Scala does not compile

我在 future recover 行中收到以下编译错误:

type mismatch; found : scala.concurrent.Future[Any] required: scala.concurrent.Future[play.api.mvc.Result]

我正在返回 Ok(),这是一个 Result 对象,为什么编译器会报错?

class Test2 extends Controller  {

  def test2 = Action.async { request =>

          val future = Future { 2 }

          println(1)

          future.map { result => {
             println(2)
             Ok("Finished OK")
           }
          }

         future.recover { case _ => {    // <-- this line throws an error
               println(3)
               Ok("Failed")
           }
         }

    }
 }

如果您仔细查看 Future.recover 方法,您会发现部分函数应该具有未来类型的子类型,在您的例子中是 Int,因为您将恢复应用于原始 Future 'future'。要修复它,您应该将其应用于映射:

future.map {
  result => {
    println(2)
    Ok("Finished OK")
  }
}.recover { 
  case _ => {    
    println(3)
    Ok("Failed")
  }
}

你忘记链了,所以像Nyavro写的那样,或者,如果你喜欢另一种风格,那么就引入一个中间变量。

def test2 = Action.async { request =>

  val future = Future { 2 }

  println(1)

  val futureResult = future.map { result => {
    println(2) 
    Ok("Finished OK")
  }}

  futureResult.recover { case _ => {    
    println(3)
    Ok("Failed")
  }}

}