Search code examples
templatesscalaplayframework-2.0

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


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

I tried this in Play 2.0, but without any luck. Is there an possible alternative?


Solution

  • Edit: sorry I think I have not translated this faithfully, and it's uglier. myobj.item could also be null so you'd 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"))
    

    Note sure if playframework has some additional sugar for such a common case.