Community contributed extensions

HTTP to Scala data binding

Like in Java, you can retrieve HTTP parameters directly from the action method signature. The method parameter’s name must be the same as the HTTP parameter’s. This section explain the difference related to specific Scala types.

Binding Option types

Sometimes you are not sure that a specific parameter will be present in the HTTP request. In this case, you want probably bind this value to an Option type:

def hello(name: Option[String]) = {
    name.map("Hello " + _ + "!").getOrElse("Please give us your name!")
}

Using Scala default parameter values

Another way to handle the case where an HTTP parameter is missing, is to specify a default value for the method parameter.

def hello(name: String = "Guest") = {
    "Hello " + name + "!"
}

An interesting side effect of this implementation is that the default parameter values are used as well for reverse routing. So for example you can ask Play to redirect to the Hello action without specifying the name parameter:

def redirectToHello = Action(hello())

Binding case classes

You can automatically ask Play to fill a more complex data structure, by specifying a case class as method parameter. For example:

case class User(name: String, email: String)

And then, defining an action method:

def hello(user: User) = user match {
    case User("guillaume", _) => "Howdy, guillaume!"
    case User(name, _) => "Hello " + name
}

The same convention apply than for binding JavaBean in Java, ie:

/hello?user.name=Guillaume&[email protected]

Note that Play will automatically generate a default constructor for your case class if you don’t define it yourself. However this constructor will be completely empty, and your cass class body will not been executed at object instantiation.


Next, there is some special features when using Scala types in Play templates