Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is @Named in Kotlin?

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
like image 359
RodParedes Avatar asked Feb 02 '26 10:02

RodParedes


1 Answers

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,
) {
}

}

like image 180
Simulant Avatar answered Feb 04 '26 00:02

Simulant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!