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. 

No comments: