Start Coding

Topics

Scala Play Framework

The Play Framework is a high-productivity web application framework for building scalable and reactive applications in Scala. It's designed to make development easy and efficient, with a focus on developer productivity and modern web application architecture.

Key Features

  • Stateless and scalable architecture
  • Built-in support for asynchronous programming
  • RESTful by default
  • Hot code reloading for rapid development
  • Powerful routing system
  • Integrated testing tools

Getting Started

To create a new Play Framework project, you'll need to have SBT (Simple Build Tool) installed. Then, you can use the following command:

sbt new playframework/play-scala-seed.g8

This will create a new Play project with a basic structure and configuration.

Basic Structure

A typical Play Framework project has the following structure:


app/
  controllers/
  models/
  views/
conf/
  application.conf
  routes
public/
  images/
  javascripts/
  stylesheets/
test/
build.sbt
    

Routing

Play uses a powerful routing system defined in the conf/routes file. Here's an example:


GET     /                       controllers.HomeController.index
GET     /hello/:name            controllers.HomeController.hello(name: String)
    

Controllers

Controllers handle incoming HTTP requests and return responses. Here's a simple controller example:


import javax.inject._
import play.api.mvc._

@Singleton
class HomeController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
  def index() = Action { implicit request: Request[AnyContent] =>
    Ok("Welcome to Play!")
  }

  def hello(name: String) = Action {
    Ok(s"Hello, $name!")
  }
}
    

Views

Play uses Scala's template engine for views. Here's a simple example:


@(title: String)(content: Html)

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>@title</title>
    </head>
    <body>
        @content
    </body>
</html>
    

Asynchronous Programming

Play supports asynchronous programming out of the box, making it easy to build scalable applications. You can use Futures and Async/Await patterns:


import scala.concurrent.{ExecutionContext, Future}
import javax.inject._
import play.api.mvc._

@Singleton
class AsyncController @Inject()(cc: ControllerComponents)(implicit ec: ExecutionContext) extends AbstractController(cc) {
  def asyncAction = Action.async {
    Future {
      // Some long-running operation
      Thread.sleep(1000)
      Ok("Operation completed!")
    }
  }
}
    

Testing

Play provides built-in support for testing your application. You can use ScalaTest or Specs2 for writing tests:


import org.scalatestplus.play._
import org.scalatestplus.play.guice._
import play.api.test._
import play.api.test.Helpers._

class HomeControllerSpec extends PlaySpec with GuiceOneAppPerTest with Injecting {
  "HomeController GET" should {
    "render the index page from a new instance of controller" in {
      val controller = new HomeController(stubControllerComponents())
      val home = controller.index().apply(FakeRequest(GET, "/"))

      status(home) mustBe OK
      contentType(home) mustBe Some("text/plain")
      contentAsString(home) must include ("Welcome to Play!")
    }
  }
}
    

Conclusion

The Scala Play Framework offers a robust and efficient platform for building web applications. Its focus on developer productivity, scalability, and modern web architecture makes it an excellent choice for Scala developers. By leveraging Play's features and integrating with other Scala libraries like Akka and Slick, you can create powerful, reactive web applications.