1

In this question, an answer says that the Application class must be defined this way:

class Application @Inject()(val messagesApi: MessagesApi) extends Controller with I18nSupport {

I understand this line as:

  • named Application
  • extends Controller
  • mixes in trait I18nSupport

How do I read/comprehend the @Inject() and (val ...) in the middle? Why is it written this way and what does this mean?

3
  • Looks like this is a general question regarding dependency injection. Sure thus would help: playframework.com/documentation/2.5.x/ScalaDependencyInjection
    – Pavel
    Apr 3, 2016 at 20:53
  • I18nSupport is trait with abstract def messagesApi: MessagesApi. You need to provide the implementation. So you define it as val messagesApi: MessagesApi. @Inject means - the constructor parameters will be provided by dependency injection. Apr 3, 2016 at 21:11
  • In addition to what @PavelOliynyk said, this issue explains that the docs are not very welcoming to newcomers. By default, Play uses Guice under the hood for DI. In the aforementioned issue, one of the commenters links to some great Guice documentation that may help.
    – Eric
    Apr 3, 2016 at 22:28

1 Answer 1

0

How do I read/comprehend the @Inject() and (val ...) in the middle? Why is it written this way and what does this mean?

  • @Inject() is called an annotation. Annotations allow to add arbitrary metadata to declarations, types, or expressions. This metadata can be queried either at runtime or at compiletime.
  • (val …) is called a primary constructor. A constructor is a subroutine which is called when you create an instance of a class, and its purpose is to set up the initial state of the object such that it is ready to use and satisfies all its invariants.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.