Recently I had a problem with @Named
qualifier in Kotlin. I thought that changing from this:
var boldTypeface: Typeface? = null
[Inject] set
into this
var boldTypeface: Typeface? = null
[Inject Named("bold")] set
or
var boldTypeface: Typeface? = null
[Inject] [Named("bold")] set
would solve my problem. But it didn't, it's not even compiling.
@Qualifier annotation is provided by javax inject package and is used to qualify the dependency. For example, a class can ask both, a GeneralComputer or a SpecializedComputer in the given example. But both these Objects will be of type Computer.
Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are: @Module This annotation is used over the class which is used to construct objects and provide the dependencies.
Dagger automatically generates code that mimics the code you would otherwise have hand-written. Because the code is generated at compile time, it's traceable and more performant than other reflection-based solutions such as Guice. Note: Use Hilt for dependency injection on Android.
To understand it better during a basic course, think module as a provider of dependency and consider an activity or the other class as a consumer. Now to supply dependency from provider to consumer we have a bridge between them, in Dagger, Component work as that specific bridge.
I had to update my answer since Kotlin improved a lot. Right now I am using Kotlin 1.0 beta 3
To properly set multiple annotations for a property you have to use @field
annotation:
@field:[Inject Named("bold")]
lateinit var boldTypeface: Typeface
Note that I am using lateinit
here so there is no need to use nullable type Typeface?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With