4

In Play 1.x you could do things like &{task?.server?.name} to print the server name if it exists or to print nothing if task or task.server were null. How can I get the same result in the 2.x scala templates?

I found some questions about doing this in general with Scala:

but those solutions are either rather verbose or require defining your own operator. Does Play provide a quick way to do this? Or if I need to define the operator myself, where should I put it so Play finds it? (I know almost nothing about Scala at this point, though I'm trying to learn)

Community
  • 1
  • 1
Brad Mace
  • 27,194
  • 17
  • 102
  • 148
  • In scala you would prefer use Options and None instead of null. You can have a look here : http://stackoverflow.com/a/6417563/595223 – kheraud Jul 11 '12 at 08:10

1 Answers1

0

There are many null-handling-related questions and answers already here so I'll concentrate only on your Play-2 related questions.

I did a quick test and it seems that the template system converts direct dereferencing of null values into empty strings. This still won't save you from a NPE if you try to call some method on the object that is passed in as null. For that you need to use some of the methods described in all these other answers. If you define a new operator you can place it any package you like and then add this line into your template:

@import some.package._

This will make everything in some.package be accessible in the template.

The usual good practice warnings still apply: try to use nulls only in interop with java. For everything else there's Option.

Igor Rumiha
  • 407
  • 3
  • 10