Home > Enterprise >  What is @Named in Kotlin?
What is @Named in Kotlin?

Time:11-17

The documentation doesn't really help me too much.

I don't understand what it is used for and why it is accompanied by @Inject?

Like in this line

@Named(AUTH_INTENT)
@Inject
lateinit var authIntent: Intent

CodePudding user response:

For most dependencies there is just one class of the requested type in scope (e.g. service implementations), so the instance to inject can be derived from the type.

However if you have multiple objects available for injection (e.g. multiple integer configuration values) you have to add the @Named annotation to specify, which one of the many instances with the same type you want to get.

https://dagger.dev/dev-guide Section: Qualifiers

@Module
class AppModule(val app: Application) {

    @Provides @Named("the_answer")
    fun providesTheAnswer(): Int { 
        return 42
    }

    @Provides @Named("zero")
    fun providesZero(): Int { 
        return 0
    }
}

// this works
class MyClass @Inject constructor(
    @Named("the_answer") val answer: Int,
    @Named("zero") val other: Int,
) {
}


// this does not work. Which parameter should get which value?
class MyClass @Inject constructor(
    val answer: Int,
    val other: Int,
) {
}

}

CodePudding user response:

As far as Kotlin is concerned, they are both just annotations.

These particular annotations are read by your dependency injection framework.
@Inject means this is a field that should have its value injected
@Name instructs the framework on how to obtain the value to inject

Details are covered by the docs for the dependency injection framework you use. I see someone has tagged the question with "dagger", but there are several other DI-systems that use the same annotation names.

  • Related