Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Dagger's 2 @Named qualifier in Kotlin

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.

like image 354
Damian Petla Avatar asked Feb 06 '15 09:02

Damian Petla


People also ask

What are qualifiers in dagger?

@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.

What is the use of dagger 2 in Android?

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.

How does dagger generate code?

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.

How does a dagger work internally?

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.


1 Answers

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?

like image 116
Damian Petla Avatar answered Oct 30 '22 15:10

Damian Petla