1
votes

I'm getting the following compilation error in the future recover line:

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

I'm returning Ok() which is a Result object, so why is the compiler complaining?

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")
           }
         }

    }
 }
2
No, you are not! :D You are returning value 2 or Ok("Failed"). This is not Java, you can't do return thisStuff else .. return that... . The last object you are returning from your method is the result... See answer below.insan-e

2 Answers

3
votes

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")
  }
}
0
votes

You forget to chain, so do like Nyavro wrote, or, if you like another style, then just introduce an intermediate variable.

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")
  }}

}