Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala and @Inject annotation

I know that the best way to deal with dependency injection in Scala is using tools that were built specifically for the language, but I working on a project that must integrate some Scala and Java code.

Then, I am using Google Guice, that implements specification JSR-330. Fortunatly, I found no problem during integration of Guice and Scala. I am using constructor injection, because I have to deal with immutability.

My question is, why in Scala we have to use the notation @Inject() in front of the constructor parameter? Why the () paranthesis? It follows an example:

class MyClass @Inject() (val another: AnotherClass) {
  // Body of the class
}
like image 466
riccardo.cardin Avatar asked Jul 28 '16 08:07

riccardo.cardin


People also ask

What is the @inject annotation?

The @Inject annotation lets us define an injection point that is injected during bean instantiation. Injection can occur via three different mechanisms. Bean constructor parameter injection: public class Checkout { private final ShoppingCart cart; @Inject.

What is inject in Scala?

Introduction to Scala Dependency Injection. Dependency Injection is the software design pattern used to simplify our logic. Dependency Injection separates our implemented methods, and interfaces provide us benefits from debugging our code easily.

What does Google @inject do?

@Inject annotates constructors and methods that determine what an object needs to be initialized. There are also a lot of other annotations that determine how Guice works. But simply annotating objects isn't enough; you also have to configure them with Guice bindings.

What is @inject annotation in Guice?

Annotation Type Inject. @Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values.


2 Answers

Otherwise, how could you tell if (val another: AnotherClass) is constructor parameter list or arguments to @Inject?

like image 103
Alexey Romanov Avatar answered Oct 05 '22 01:10

Alexey Romanov


It is all about the syntax of annotating a constructor. Scala requires a constructor annotation to have one (and exactly one) parameter list (even if it is empty)

class Bar @Fooable() ( val i : Int) {

}

What would the i parameter belong to below: The annotation or the Bar class?

class Bar @Fooable( val i : Int) {

}
like image 38
raphaëλ Avatar answered Oct 05 '22 02:10

raphaëλ