Thargor Thargor - 28 days ago 5
Java Question

Java object i use in scala are getting created several times

i work with the Play Framework 2.5 and i use several JAVA classes trough scala in my templates. I create the object one times with

@import MyClass;
@foo = @{new MyClass(bar)}


With only that code, the contructor of MyClass is not called (i have put a debug output in the constructor too check a call of it)

Now i use a function of that JAVA class like

@foo.getMeSomeBar()


somewhere in the template. Now, the constructor is called. The Problem: every time i use a function of that class in the same template, the constructor is called.

The same problem occurs, if i pass that scala variable to another template like

@otherTemplate(foo)


Every time foo is used in otherTemplate the constructor is called.

Is this the desired behavior? If yes, why? If no, how can i avoid it?

EDIT: if i create the MyClass object in the Controller and pass it from there to the templates the constructor is only called one times. But in some cases if have to create the MyClass in the template or i have to change a lot of classes.

Answer

According to the documentation, you should not use the @foo = @{ ... } to define a reusable value. The preferred way is to do

@defining(new MyClass(bar)) { foo =>

  @foo.getMeSomeBar()

  ...

  @otherTemplate(foo)

}

Your way may have unexpected results, such as re-running the code in your block every time it is called.