Skip to main content

Qualifier

You can use the @Qualifier annotation to distinguish between different instances of the same type.

First, define the qualifier annotations with @Qualifier.

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class ID1

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class ID2

Then, use the annotations to specify the qualifier when providing the instances.

@ID1
@Provide
fun provideDB1(): DB {
DB.create("id1")
}

@ID1
@Provide
fun provideDB2(): DB {
DB.create("id2")
}

Finally, use the qualifiers to inject the instances you need.

class Repository(
@ID1
val db1: DB,
@ID2
val db2: DB
)

You can also use qualifier annotations when calling the inject() function.

val db1 = inject<DB>(ID1())
val db2 = inject<DB>(ID2())

This allows you to provide and inject multiple instances of the same type without ambiguity.

Distinguishing with Qualifier members

Qualifier annotations can also have members to further distinguish between instances.

For example, you can use the enum class like this:

enum class QualifierType {
ID1,
ID2
}

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class EnumQualifier(val type: QualifierType)
@EnumQualifier(QualifierType.ID1)
@Provide
fun provideDB1(): DB {
DB.create("id1")
}

@EnumQualifier(QualifierType.ID2)
@Provide
fun provideDB2(): DB {
DB.create("id2")
}
val db1 = inject<DB>(EnumQualifier(QualifierType.ID1))
val db2 = inject<DB>(EnumQualifier(QualifierType.ID2))

The following types can be used as qualifier members:

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class IntQualifier(val value: Int)

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class FloatQualifier(val value: Float)

The following types are currently not supported:

annotation class OtherAnnotation(val value: String)

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class AnnotationQualifier(
val value: OtherAnnotation // Not supported!
)

Qualifier members can have multiple values ​​and can have default values:

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class CustomQualifier(
val int: Int,
val string: String = "default",
)

Named annotation

You can also use the @Named qualifier to distinguish between different instances of the same type based on a string value.

@Named("db1")
@Provide
fun provideDB1(): DB {
DB.create("id1")
}

@Named("db2")
@Provide
fun provideDB2(): DB {
DB.create("id2")
}
class Repository(
@Named("db1")
val db1: DB,
@Named("db2")
val db2: DB
)
val db1 = inject<DB>(Named("db1"))
val db2 = inject<DB>(Named("db2"))
Migration (VERSION 1.2.0)

The inject() API for Named has changed since v1.2.0.

// Until v1.1.0
val db1 = inject<DB>("db1")
val db2 = inject<DB>("db2")

// Since v1.2.0
val db1 = inject<DB>(Named("db1"))
val db2 = inject<DB>(Named("db2"))