Scala – How to create a global variable with Play Framework 2.0

playframeworkplayframework-2.0scala

How do I create a global object/variable in Play Framework 2.0 using Scala?

I want to create a object that once instantiated, can persist between multiple controller actions so that different actions can still call on the same object (because initializing the object is very expensive).

Is this possible without storing it into the DB? I tried sticking the object into a the Global object for the onStart method as shown here:

http://www.playframework.org/documentation/2.0/ScalaGlobal

This was my code:

(in the root application folder)

object Global extends GlobalSettings {

  override def onStart(app:Application) {
    var foo = new Foo
    }
  }

}

And in my controller actions I try just calling the variable by name, but it didn't work.

Best Answer

If your globals also need to be available to the methods in Global, put them in Global.scala like so:

package object globals {
  lazy val abc = Play.maybeApplication.flatMap(_.configuration.getString("abc")).getOrElse("default_value_of_abc")
  lazy val someActor = Akka.system.actorOf(Props[SomeActor], name = "someActor")
}

And then use it in your controllers like this:

println(globals.abc)
globals.someActor ! SomeMessage

UPDATE

The documentation has since been updated how add Global.scala in an idiomatic Play! way, with docs for both Scala and Java.

Related Topic