ps0604 ps0604 - 22 days ago 5
Scala Question

Accessing Play Singleton methods

I have the following Play Singleton:

package p1

@Singleton
class MySingleton @Inject() (system: ActorSystem, properties: Properties) {

def someMethod = {
// ........
}
}


When I try to access the method
someMethod()
from a class, even when I import the package, I get a compilation error saying that the method is not found. How to fix this?

Answer

First of all in order to access the methods of a class you have to have the instance of the class. As you are using the dependency injection, You need to inject the singleton class first into the class where you want to use the method. So first declare class Lets say Foo and using the Guice annotation @Inject inject the class MySingleton and then once you get the reference (instance) of the class. You can invoke the someMethod using the .

If you want to access the method in a class say Foo. You need to inject the class MySingleton.

import p1.MySingleton

class Foo @Inject() (mySingleton: MySingleton) {

  //This line could be any where inside the class.
  mySingleton.someMethod

}

Another way using Guice field injection.

import p1.MySingleton

class Foo () {
  @Inject val mySingleton: MySingleton

  //This line could be any where inside the class.
  mySingleton.someMethod

}