1. @named of dagger2 cannot be used

When Kotlin uses Dagger2, the @module annotation class has methods that return two types of the same type, so we need to use @named to separate the annotation. Otherwise, we will get an error when building. In normal case, annotate method1 with @named (”example1″); Annotate method2 with @named (“example2”). The places used are then marked with @Inject@Named(“example1”). That completes the dependency. However, kotlin found that the null pointer did not depend on success. I tried @qualifier again to customize an annotation. Because @named also relies on @qualifier to generate.

This is how Java generates an annotation

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@interface FS {
}
Copy the code

This is how Kotlin generates an annotation

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
internal annotation class FS
Copy the code

Then I use @fs instead of @named to annotate methods and variables.

Solutions:

Then in the dagger2 issue it says @named with @inject @inject so @inject @field:Named(“example1”) while the @module method continues to be labeled with @named and the modifier succeeds. You can do the same with @field:FS, which is also successful.

Method one:

//BeanModule.kt
@Named("fs")
@Provides
fun showCityFS(a): City {
    var city = City()
    city.setName("fs")
    return city
}

//MainActivity.kt
   @Inject @field:Named("fs")
    lateinit var city: City
Copy the code

Method 2:

//BeanModule.kt
@FS
@Provides
fun showCityFS(a): City {
    var city = City()
    city.setName("fs")
    return city
}
//MainActivity.kt
   @Inject @field:FS
    lateinit var city: City
Copy the code

Thanks for Your Watching, this article is updated from time to time.