Running Play Framework + Scala Apps on Heroku

Building Play Framework apps with Scala is all the rage right now. And for good reason… It’s never been easier to build and deploy JVM-based web apps! Lets walk through how to build a Play app with Scala and then deploy it on the cloud with Heroku.

Step 1) Install the Play Framework (make sure you have at least version 1.2.3)

Step 2) Install the Play Scala module:

play install scala

Step 3) Create a new Play app with Scala support:

play new playwithscala --with scala

Step 4) Start the app:

cd playwithscala
play run

Step 5) Open the app in your browser:

That was easy! Lets spice this up a bit before we deploy it on Heroku by adding a custom model, view, and controller.

Step 1) Create a new app/models/Widget.scala file containing:

package models
case class Widget(id: Int, name: String)

Step 2) Create a new app/views/Widget/list.scala.html file containing:

@(widgets: Vector[models.Widget])
<!DOCTYPE html>
    <body> { widget => 
            Widget =</br>

Step 3) Create a new app/controllers/WidgetController.scala file containing:

package controllers
import play._
import play.mvc._
object WidgetController extends Controller {
    import views.Widget._
    import models.Widget
    def list = {
        val widget1 = Widget(1, "The first Widget")
        val widget2 = Widget(2, "A really special Widget")
        val widget3 = Widget(3, "Just another Widget")
        html.list(Vector(widget1, widget2, widget3))

Step 4) Test out the new code by going to:

It works! And we didn’t even need to reload the server! But lets clean up that URL a bit. Edit the conf/routes file and change “Application.index” to “WidgetController.list”:

GET     /                                       WidgetController.list

Now load the new URL:

That was easy but now we want to show our friends. So lets deploy it on Heroku.

Step 1) Install the Heroku command line client on Linux, Mac, or Windows

Step 2) Login to Heroku from the command line:

heroku auth:login

Step 3) Heroku uses git for application upload, so create a .gitignore file containing:


Step 4) Create a git repo, add the files to it, and commit them:

git init
git add .
git commit -m init

Step 5) Create the new application on Heroku:

heroku create -s cedar

This provisions a new application on Heroku and assigns a random name / URL to the app.

Step 6) Deploy the application:

git push heroku master

The application will now be assembled and deployed on Heroku.

Step 7) Open the application in the browser:

heroku open

Tada! Your Play + Scala app is now running on the cloud!

At JavaOne I showed this to Bill Venners (creator of ScalaTest). He then moved the website (a Play + Scala app) to Heroku! Cool stuff!

Let me know if you have any questions.

Learning Scala: Function Literals

I’ve gradually been learning Scala over the past few months and I really have been enjoying it. For me Scala is like Shakespeare. It seems familiar and totally foreign at the same time. I don’t enjoy Shakespeare plays nearly as much as someone who has taken the time to learn the language of Shakespeare. Some have interpreted Scala being “familiar yet totally foreign” as Scala being “hard” but I’d say it’s just different. With Scala there is probably more about programming that I need to unlearn than to learn. My perspectives on programming languages have been shaped by the ones I’ve used most (Java, ActionScript, etc). And now my perspecives are being reshaped. It might take some time and work but I believe that using Scala will soon be very enjoyable for me.

Ok, enough fluff lets see some code!

My friend Mike Slinn and I have been learning BlueEyes – a lightweight Scala web 3.0 framework. We encountered a piece of Scala that seemed strange and unfamiliar to us:

get { request =>
  // do something

To a Java developer like me this was pretty foreign. I was able to understand this after I encountered Function Literals in the free Scala for the Impatient book. So let me break down what is happening here with another example. Lets start with writing a regular function that takes a Char parameter and returns a Boolean if the provided Char was the letter “l”:

def lls(p: Char): Boolean = { p == 'l' }

This is a pretty straight forward (albeit slightly verbose) function definition. Oh, and I should mention that if you download Scala and run the REPL (a command line interpreter), then you can actually try this code yourself. To start the Scala REPL just run the “scala” command.

Ok, lets test out that function:

lls('p') // outputs false
lls('l') // outputs true

That should all be somewhat familiar looking for a Java developer. But here is where things begin to look more foreign. The StringOps class in Scala has a count method that takes something very peculiar looking. From the ScalaDoc:

def count (p: (Char) ⇒ Boolean): Int

That is saying that count takes a function as an argument. Scala is this wonderful blend of Object Oriented and Functional so this is instantly strange to the Java developer in me. In this case the function that count is taking must have a single parameter of type Char and then return a Boolean. So lets try to pass the lls function to count on a StringOps instance. Somehow with Scala’s Type Inference system we can just use a regular double-quoted String and Scala will figure out that we need a StringOps instead. So let’s create a StringOps object and call count on it passing it the lls function:

"Hello".count(lls) // outputs 2

I could have assigned “Hello” to a variable and done it that way but opted to just make the count call without assigning it. So count correctly took the lls function and used it to count the number of “l” Chars in the String (or SpringOps). That all works as expected.

But, there is another (prettier) way to do the same thing:

"Hello" count lls // outputs 2

We can drop the dot operator and parenthesis and everything still works. But there is another way… Instead of referencing a function we can just pass the function definition directly into the count method:

"Hello" count { p:Char => p == 'l' } // outputs 2

This is a Function Literal – or as Dick Wall tells me, a predicate in this case since it returns a Boolean. A Function Literal is a short way to define a function that takes only one parameter and returns what is needed by whatever the function is being passed to. In this case the function parameter is still a Char with an identifier of “p” and the function body simply compares “p” with the ‘l’ Char. In Scala the value of the last statement in a function is returned. So the Boolean is returned from the function. That type is inferred. And the Char type declaration on “p” could have been left off and inferred making it:

"Hello" count { p => p == 'l' } // outputs 2

Now that code I started with is making a lot more sense!

But it doesn’t stop there. With Scala we can be even more concise:

"Hello" count { _ == 'l' } // still outputs 2

Now I must admit that I haven’t really learned what that “_” thing does. So I don’t totally understand this code yet. But like learning to understand Shakespeare we have to take it one step at a time. I will leave that to another day and maybe another blog post. I hope this was helpful for other Scala noobs. Let me know what you think and if you have any questions.

Heroku Java User Group Tour Part 1: Los Angeles and Salt Lake City

This week I’m starting a Java User Group tour where I’ll be travelling to JUGs around the US (or maybe world). On the tour I’ll be giving a talk about Running Java, Play! and Scala Apps on the Cloud. Here is the description:

Heroku is a Polyglot Cloud Application Platform that makes it easy to deploy Java, Play! and Scala apps on the cloud. Deployment is as simple as doing a “git push”. This session will teach you how to instantly deploy and scale Java, Play! and Scala apps on Heroku.

I’m still scheduling JUGs but here are the first two I’ll be doing:

There will be more to come and if you’d like this talk at your local Java User Group, let your leader know and have them email me: jw <at> heroku <dot> com

Hopefully see you at your local JUG!

Getting Started with Scala on Heroku

Over the past year I’ve been gradually learning Scala and I think it’s fantastic! So I’m incredibly excited that Scala now runs on Heroku! Of course you can use the standard Java on Heroku / Maven method of running Scala on Heroku. But as of today you can also use sbt (the Scala Build Tool) to run Scala apps on Heroku. If you are new to Heroku, it is a Polyglot Cloud Application Platform. Put very simply:

Heroku = Polyglot + Platform as a Service (PaaS) + Cloud Components

If you want to try out Scala on Heroku, here are a few quick steps to get you started:

  1. Create a Heroku account
  2. Install the Heroku command line client on Linux, Mac, or Windows.
  3. Install git and setup your SSH key
  4. Install sbt 0.11.0
  5. Login to Heroku from the command line:

    heroku auth:login
  6. Create a file named build.sbt containing:
    scalaVersion := "2.9.1"
      val stage = TaskKey[Unit]("stage", "Prepares the project to be run, in environments that deploy source trees rather than packages.")
      stage in Compile := {}

    This adds the “stage” task which is used for the build on Heroku.

  7. Create a project/ file containing:

    This tells sbt which version of sbt to use.

  8. Create a very simple Scala app in src/main/scala/Hello.scala containing:
    object Hello extends App {
      println("hello, world")
  9. Test the app locally by running:
    sbt run

    You should see something like:

    [info] Set current project to default-0c17d0 (in build file:/home/jamesw/projects/helloscala/)
    [info] Running Hello 
    hello, world
    [success] Total time: 1 s, completed Sep 7, 2011 4:17:01 AM
  10. Create a .gitignore file containing:
  11. Create a git repo, add the files to it, and commit them:
    git init
    git add .
    git commit -m init
  12. Create a new app on Heroku using the Cedar stack:
    heroku create -s cedar
  13. Upload your app to Heroku using git:
    git push heroku master
  14. Run the app on Heroku:
    heroku run "sbt run"

    Voilà! You just ran Scala on the Cloud!

You can get the full code for this project on github:

That was a very simple example to get you started. Visit the Heroku Dev Center to continue learning about how to use Scala on Heroku. And let me know if you have any questions.

Setup Play Framework with Scala in IntelliJ

UPDATE: This is only for Play 1.x with Scala. Getting Play 2 projects (Java or Scala) working in IDEA is now as easy running “play idea” and then opening the project.
Update 2: I’ve posted a new video showing how to create and run Play2 apps in IntelliJ.

Yesterday at the Programming Summer Camp a group of us were working together to learn the Play Framework. Once we were able to get the basics working we wanted to get everything working in IntelliJ IDEA. Due to a lack of good documentation on the subject things did not go smoothly until we figured out the right “magical incantations”. We did eventually get it working so I wanted to document the steps we took.

  1. Add Scala support to Play:
    play install scala
  2. Create a new Play project with Scala support:
    play new foo --with scala
  3. Have Play create an IntelliJ Module Descriptor:
    play idealize foo
  4. Run the app:
    play run foo
  5. Access the app in a browser to generate some source files we will use later:
  6. Shutdown the Play server.
  7. Currently the Play Scala Module (version 0.9.1) only supports Scala 2.8.1 so download and extract that version.
  8. Create a new project (from scratch) in IntelliJ. The location should be the same as the directory where the Play project was created. Un-check the “Create module” option.
  9. In the Project Structure window, with “Modules” selected, click the “+” button to add a new module to the project.
  10. Select the “Import existing module” option and then point it to the generated .iml file.
  11. With the module now selected, select the content root block for the module (mine is /home/jamesw/projects/foo). Then select the “tmp/generated” directory in the tree on the right and press the “Sources” button. The HTML template pages are converted to .scala source files by Play and we need these source files to be included in the project along with the regular source files in the app directory.
  12. Select “Global Libraries” in the Platform Settings on the left and add a new Java Library named “scala-compiler-2.8.1”. Then press the “Attach Classes…” button and navigate to the “lib” directory in your Scala 2.8.1 directory. Then select the “scala-compiler.jar” and “scala-library.jar” files.
  13. Add another Global Library named “scala-library-2.8.1” containing the “scala-dbc.jar”, “scala-library.jar”, and “scala-swing.jar” files.
  14. Press the “Apply” button to save the Global Libraries configuration.
  15. Select “Modules” and then the “Dependencies” tab. Press the “Add…” button and select “Library” to add a new library to the module. Select “scala-library-2.8.1” and then press the “Add Selected” button to add it to the Dependencies.
  16. Select the “Scala” Facet in the module and set the Compiler library to the “scala-compiler-2.8.1” option.
  17. Save the Project Structure by pressing the “Ok” button. Make sure the project now builds without any errors.
  18. To run the Play server from IntelliJ a new Run Configuration must be configured. To create a new Run Configuration select “Run” from the main IntelliJ menu and then select “Edit Configurations”.
  19. Press the “+” button and select “Application” from the list of Run Configuration types.
  20. Set the name to “Play Server”.
  21. Set the Main class to “play.server.Server”.
  22. Set the VM Parameters to:
  23. De-select the “Make” option in the “Before Launch” section.
  24. Press the “Ok” button to save the configuration.
  25. Run the Play Server by selecting “Run” from the “Run” IntelliJ menu and verify that the application still works by opening the application in a browser.

It is so much easier to figure this stuff out with a group of people. That is just one of the many reasons why the Programming Summer Camp is a great event!

Let me know if you have any questions or problems.