Friday, September 28, 2012

Variables in Scala files for Play 2.x

The scala html files for Play 2.x will eventually be compiled in classes/methods. Each one has a signature to allow type-safe parameter passing from controller to the view. But sometimes we need to include a script in the page and that is when the need for local variables may occur.
For instance I want to make sure I add HTML only if the object is not null. In JAVA this would be equivalent to:
Feature f = features.getFeature(featureName);
if (f != null) {
  .... use the feature object ....
}
or if I need to iterate:
for (Feature f : features) {
  if (f == null) continue;
  .... use the feature object ....
}
Note that I test the object for null and use "continue" instead of enclosing everything in the if block. It is a matter of preference - I think it makes the code more readable.

Two problems arise when trying to do the same in Scala in the html pages:

  • declaring local variables in Play scala pages is quite cumbersome
  • there is no "continue" in Scala.

Here are a few workarounds for the issues mentioned above:


  • Use "Option". Option is a replacement for checking for null. The map is created only if not null. In this case a map of one element is created and is assigned to “feature”.



@Option(features.getFeature(featureName)).map {feature=>
........}
  • What if there are more that one?
@Option(features.getFeature(featureName)).map {feature=>      @Option(1).map (f2 =>       }}
  • You can also use for loops.
@for(feature1 <- Option(features.getFeature(featureName));     f2 <- Option(1)) {
}

  • If List is used instead of Option, the for loop will be executed once for each item in the List. 

Thursday, June 28, 2012

Upgrade from Play 2.0.1 to 2.0.2

Say you have a project in Play 2.0.1, but guess what? There is a new (minor) version out there that might just fix a bug you care about. How do you go about upgrading?
Well, first you need to download the new Play 2.0.2 framework and replace the old one. Then, you need to edit a couple files in  your project in order to make it compatible:

  • edit [appName]/project/build.properties and change sbt version from 0.11.2 to 0.11.3. Like this:
    sbt.version=0.11.3
  • edit [appName]/project/plugins.sbt and change the version of play from 2.0.1 to 2.0.2. Like this:
    addSbtPlugin("play" % "sbt-plugin" % "2.0.2")
That's it! Now launch play again and you should see that it updates a bunch of libraries and then its' ready.
Additionally if you are using Eclipse IDE, you might need to re-eclipsify your app in order to fix the Eclipse project classpath to point to the new 2.0.2 directory.