J. Doe
J. Doe

Reputation: 23

Scala Play 2.5 Turning an Action into A Result

In a Play scala project, I'm returning an object inside of a Controller with the type:

play.api.mvc.Action[play.api.libs.json.JsValue however, play is complaining that it is expecting play.api.mvc.Result. According to the docs, an Action is a function that handles a request and generates a result.

def myController = mySpecialFunction.asyc(prase.tolerantJson) { implicit request => {
        for {
            ... do some stuff ...
        } yield {
            myFunction()
        }
    }
}

In this case, myFunction has a return type of play.api.mvc.Action[play.api.libs.json.JsValue.

I want to return a result, and I'm not sure how to correctly call this function

Upvotes: 0

Views: 927

Answers (2)

Jamie
Jamie

Reputation: 6124

If you want to solve the problem as-is, you can pass request to the result of myFunction():

def myController = mySpecialFunction.asyc(prase.tolerantJson) { implicit request => {
        for {
            ... do some stuff ...
        } yield {
            myFunction()(request)
        }
    }
}

This works because there is a method Action#apply which will be invoked with the request instance and return a Future[Result].

The documentation for the apply method: https://www.playframework.com/documentation/2.5.x/api/scala/index.html#play.api.mvc.Action

Upvotes: 0

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Your Action.async block expects a function from request to Future[Result].

Now, your myFunction() is inside the yield block returning JsValue as return type. If your for comprehension is on Futures, then the output of the for-comprehension becomes Future[JsValue]. But play expects Future[Result]. Transform your result into Future[Result]. So that your final output type should be Future[Result].

for example

Action.async { req =>
  val resultFuture = 
    for {
      _ <- getUsersFuture
      _ <- doSomethingFuture
    } yield (myFunction)

  resultFuture.map { json => Ok(json) }
}

Upvotes: 1

Related Questions