Thargor Thargor - 1 year ago 55
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


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


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 Source

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 =>





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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download