Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala-guice and assisted injection

I have been using google-guice with the assisted inject mechanism for quite some time now. As i am in scala, and just discover scala-guice, i'm interested in using it as well. However i'm confused as to how to use assisted injection with it. There is no example of using assisted inject with it.

Hence my question here is: is it possible to use assisted injection with scala-guice, if yes, please could anyone provide a simple example ?

Moreover for google-guice i use the following libs: javax.inject.jar, guice-3.0.jar, guice-assistedInject.jar. In this case shall i just remove guice-3.0.jar ?

like image 789
MaatDeamon Avatar asked Dec 21 '13 18:12

MaatDeamon


1 Answers

It is by all means possible to use assisted inject in Scala. If scala-guice does not provide tools for it, you just can use assisted inject API directly:

trait Entity { ... }

class EntityImpl @Inject (
  @Assisted assistedDep: AssistedDependency, 
  normalDep: NormalDependency
) extends Entity { ... }

trait EntityFactory {
  def create(assistedDep: AssistedDependency): Entity
}

class YourModule extends AbstractModule with ScalaModule {
  def configure {
    install(new FactoryModuleBuilder()
      .implement(classOf[Entity], classOf[EntityImpl])
      .build(classOf[EntityFactory])
    )
    bind[NormalDependency].to[NormalDependencyImpl]
  }
}

True, it is not very pretty, but it gets the work done.

Also, you absolutely should not remove guice-3.0.jar. Why did you think of it in the first place? javax.inject.jar contains JSR-330 annotations, guice-3.0.jar contains Guice itself, and guice-assistedinject-3.0.jar contains assisted inject extension. All these jars are important if you need Guice with assisted inject support.

like image 159
Vladimir Matveev Avatar answered Nov 15 '22 07:11

Vladimir Matveev