Home > database >  "cannot be provided without an @Provides-annotated method" - Hilt
"cannot be provided without an @Provides-annotated method" - Hilt

Time:11-29

The following code will not compile. It complains with:

Mammals cannot be provided without an @Provides-annotated method.


@HiltViewModel
class AnimalsViewModel @Inject constructor(private val animalRepository: AnimalRepository) : ViewModel() {

    @Mammals
    @Inject lateinit var mammals: Mammals

    @Fish
    @Inject lateinit var fish: Fish

    fun getListOfAnimals(): List<String> {
        val orgs = rescue.getOrganization()
        var m = "type = "   mammals
        var f = "fish = "   fish

        return animalRepository.getAnimals()
    }
}


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

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

@Module
@InstallIn(SingletonComponent::class)
object AnimalsModule {
    @Provides
    @Mammals
    fun provideMammals(): String {
        return "whale"
    }

    @Provides
    @Fish
    fun provideFish(): String {
        return "carp"
    }
}

CodePudding user response:

You are trying to inject annotation class, not the thing you annotated with it.

@Mammals
@Inject lateinit var mammals: Mammals

Thus, Hilt can't find Mammals because you do not provide them. You provide a String that is annotated with @Mammals and that is what you should ask from Hilt.

@Mammals
@Inject lateinit var mammals: String
  • Related