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

时间:2016-12-02 02:40:37

标签: scala playframework playframework-2.5

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

  

类型不匹配;发现: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")
           }
         }

    }
 }

1 个答案:

答案 0 :(得分:3)

If you take closer look at the Future.recover method you'll see that partial function should have subtype of future's type, in your case Int, because you apply recover to original Future 'future'. To fix it you should apply it to mapped:

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