ps0604 ps0604 - 11 days ago 4
Scala Question

Returning non-Future in Play for Scala

I have the following method that returns a list of Strings in a Play for Scala application:

def example = Action.async { request =>

val access = getAccess()

if (access > 0) {
val future = MyObject.intensiveMethod
future.map {
result => {
val list = result.asInstanceOf[List[String]]
val json = JsObject(Seq(
"list" -> Json.toJson(list)
))
Ok(json)
}
}
}
else {
val json = JsObject(Seq(
"msg" -> JsString("error!")
))
Ok(json)
}


}

The code does not compile with the following error, because if access = 0 the result is not a Future:


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


How to fix this?

Answer

Then wrap it with Future, e.g.:

  Future.successful(Ok(JsObject(Seq(
      "msg" -> JsString("error!")
  ))))
Comments