0
votes

Whenever I am using @Named annotation in my code I am always getting "java.lang.String cannot be provided without an @Inject constructor or an @Provides-annotated method." this error Please find the code snippets below but before checking the code let me clear you what I want to achieve and what is the exact issue I am facing. So I am trying to keep two functions in my module file which return same type as String for this I am trying to use @Named annotation and after this I am getting the above mentioned error and If I only keep one function for type String then my project is running without any error.

This is my Component Class

@Singleton
@Component(modules = [GeneralModules::class])
interface MainComponent {

    fun dummyString():String
}

This is my Module class

@Module
class GeneralModules {

     @Provides
    @Singleton
    @Named("name1")
    fun getDummyString1(): String{
        return "some name"
    }

   @Provides
   @Singleton
   @Named("name2")
   fun getDummyString(): String{
       return "some name"
   }

}

This is how I am using inside the Activity class

@Inject
@field:Named("name1")
lateinit var name1: String

@Inject
@field:Named("name2")
lateinit var name2: String

So if I removed the @Named from Module file, delete one function and remove @field:Named code from activity it will run without any error.

1

1 Answers

1
votes

You can use an annotation class with the @Qualifier of javax.inject.Qualifier

Qualifier file

@Qualifier
annotation class Name1

@Qualifier
annotation class Name2

Module Class

@Module
class GeneralModules {

    @Provides
    @Singleton
    @Name1
    fun getDummyString1(): String{
        return "some name"
    }

    @Provides
    @Singleton
    @Name2
    fun getDummyString(): String{
        return "some name"
    }
}

code inside the Activity class

@Inject
@Name1
lateinit var name1: String

@Inject
@Name2
lateinit var name2: String