Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger 2 static provider methods in kotlin

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 providesA() {
  return A();
}

I was wondering how does one go about doing this in kotlin? I've tried

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

But I get the error message:

@Provides methods can only be present within a @Module or @ProducerModule

I'm guessing there's something going on here with the companion object, however I'm quite new to Kotlin and I'm unsure of how one can do this. Is it even possible?

Thanks!

like image 608
Fred Avatar asked Jul 03 '17 21:07

Fred


3 Answers

Although I think zsmb13's solution is better, I found another solution which works

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

  // add other non-static provides here
}

However, note that there will be two generated classes: AModule_ProvidesAFactory and AModule_Companion_ProvidesAFactory rather than the one AModule_ProvidesAFactory class for the case with an object instead of a class with a companion object

like image 81
Omar El Halabi Avatar answered Oct 19 '22 03:10

Omar El Halabi


I can't test it right now, but I think this should work:

@Module
object AModule {
    @JvmStatic
    @Provides
    fun providesA(): A = A()
}
like image 50
zsmb13 Avatar answered Oct 19 '22 03:10

zsmb13


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.

like image 19
Pavneet_Singh Avatar answered Oct 19 '22 03:10

Pavneet_Singh