Search code examples
scalaplayframework

Cannot understand Scala method definition


This is some code from Alvin Alexander's minimal Scala Websocket server.

package controllers

import play.api.mvc._
import play.api.libs.streams.ActorFlow
import javax.inject.Inject
import akka.actor.ActorSystem
import akka.stream.Materializer
import models.SimpleWebSocketActor
import play.api.libs.json._

class WebSocketsController @Inject() (cc: ControllerComponents)(implicit system: ActorSystem)
extends AbstractController(cc)
{

    def index = Action { implicit request: Request[AnyContent] =>
        logger.info("index page was called")
        Ok(views.html.index())
    }
}

What I'm curious about is the method definition for index. The notation is different to the normal method definition I've seen in Scala. Could someone explain what is going on here, and possibly point to some docs on this syntax? I haven't been able to find anything.


Solution

  • This definition is a combination of several syntax features of Scala but in the end there's nothing that special about it.

    It's equivalent to something like this:

    def index = {
      
      def handleRequest(request: Request[AnyContent]) = {
        implicit req = request
    
        logger.info("index page was called")
        Ok(views.html.index())
      }
    
      Action.apply(handleRequest) // Replaced by Action(...), then Action { ... }
    }