0
votes

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?

2
Could you show how are you injecting and using MySingleton and someMethod?michaJlS
I'm not injecting the method, I'm just declaring the import, is that the issue?ps0604

2 Answers

2
votes

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

}
0
votes

It's not an actual Scala singleton, so you cannot access someMethod statically. The @Singleton annotation tells the DI framework to only instantiate one of the MySingleton class within the application, so that all components that inject it get the same instance.

If you want to use someMethod from a class called Foo, you would need to do something like this:

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

   // call it somewhere within the clas
   ms.someMethod()

}