Dagger 2 static provider methods in kotlin

后端 未结 5 1521
梦毁少年i
梦毁少年i 2020-12-05 09:20

With the recent versions of dagger 2 one of the improvements made are the possibility of having static provide methods. Simply so:

@Provides
static A provide         


        
5条回答
  •  悲哀的现实
    2020-12-05 09:48

    Now Dagger2 (version 2.26) support companion objects in @Module annotated classes in kotlin withthouh @Module and @JvmStatic annotations

    Better support for binding declarations within Kotlin companion objects of @Module annotated classes.

    Update dagger dependencies to 2.26 version as

    def dagger_version = "2.26"
    //dagger
    implementation "com.google.dagger:dagger:$dagger_version"
    kapt "com.google.dagger:dagger-compiler:$dagger_version"
    
    //If you're using classes in dagger.android you'll also want to include:
    implementation "com.google.dagger:dagger-android:$dagger_version"
    implementation "com.google.dagger:dagger-android-support:$dagger_version"
    kapt "com.google.dagger:dagger-android-processor:$dagger_version"
    

    so now you can use

    @Module
    class AModule {
    
      companion object {
    
        @Provides
        fun providesA(): A = A()
      }
    
    }
    

    Important: Soon, adding @Module on companion objects in @Module classes will raise an error.

    Note: For backwards compatibility, we still allow @Module on the companion object and @JvmStatic on the provides methods. However, @Module on the companion object is now a no-op and all of its attributes (e.g. "includes") will be ignored. In future releases, we will make it an error to use @Module on a companion object.

提交回复
热议问题