I have a singleton class:

@Singleton
class Inject_Class_A @Inject()(
                            wsClient: WSClient,
                          )(implicit executionContext: ExecutionContext) {
// ... does something

}

I have another main class in which I want to inject the previous class, it also have other construct parameters. IDE says it is syntactically correct:

class Main_Class @Inject()(
                           inject_class_A: Inject_Class_A,
                           implicit val executionContext: ExecutionContext
                           )(key: String, value: String) {

// ... does something different using inject_class_A
}

Now I want to create objects as:

val main_class = new Main_Class(key: "KEY", value:"VALUE")

Ofcourse it gives error:

Unspecified value parameters: inject_class_A: Inject_Class_A, executionContext: ExecutionContext

I tried this way also:

class Main_Class(key: String, value: String) {

  @Inject val inject_class_A: Inject_Class_A = new Inject_Class_A()

// ... does something different using inject_class_A
}

But this doesn't work as I don't have wsClient: WSClient and executionContext: ExecutionContext and these I get only from injection only.

2

There are 2 best solutions below

0
Jorn On BEST ANSWER

With standard Guice, you can either have a class injected or instantiate it yourself. Not both at the same time. You could inject into an existing instance, but that's ugly. If you need an injected instance with runtime-determined parameters, you should look into Assited injection.

1
Gaël J On

It's a bit unclear what you're trying to achieve with this pattern, thus my answer may not fit your use case.

One option could be to use a "wrapper" class:

// No automatic injection for this class
// Move implicit parameter at the end for ease of instantiation 
class Main_Class (inject_class_A: Inject_Class_A)
                 (key: String, value: String)
                 (implicit val executionContext: ExecutionContext) {
}

@Singleton
class Wrapper @Inject()(inject_class_A: Inject_Class_A)
                       (implicit val executionContext: ExecutionContext) {

  // Manual instantiation of Main_Class
  // Implicit automatically passed
  val main1 = new Main_Class(inject_class_A)("key", "value")

}