Johann
Johann

Reputation: 29867

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

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"
    }
}

Upvotes: 1

Views: 80

Answers (1)

TheLibrarian
TheLibrarian

Reputation: 1888

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

Upvotes: 2

Related Questions