Working with an empty object in a template, how to avoid a NullPointerException?

In Play 1.2, I use something like ${myobj?.item?.subitem}.

I tried this in Play 2.0, but with no luck. Is an alternative possible?

Thanks for the help.

+3
source share
1 answer

Edit: Sorry, I think I did not translate this in good faith, and it is uglier. myobj.itemcan also be null, so you have to wrap it in Option(_):

@Option(myobj).flatMap(i => Option(i.item)).flatMap(s => Option(s.subitem)).getOrElse("empty")

or

@((for {o <- Option(myobj)
        item <- Option(o.item)
        subitem <- Option(item.subitem)
   }).getOrElse("empty"))

Please note that if for such a normal case in the playframework there is additional sugar.

+2
source

All Articles