1

I'm using Dagger2, and would like to use my app's version string in an extension function for a third party class. The app exposes the version as so currently:

BuildConfigProvider.kt

interface BuildConfigProvider {

    val version: String

}

AndroidBuildConfigProvider.kt

class AndroidBuildConfigProvider @Inject constructor(
    context: Context
): BuildConfigProvider {

    override val version = BuildConfig.VERSION_NAME
}

AndroidModule.kt

@Module
class AndroidModule(private val app: Application) {

    @Provides
    @Singleton
    fun providesApplication(): Application = app

    @Provides
    @Singleton
    fun providesContext(): Context = app

    @Provides
    @Singleton
    fun providesBuildConfigProvider(provider: AndroidBuildConfigProvider)
            : BuildConfigProvider = provider


}  

I saw this piece of code in a different extension function and decided to follow the pattern

private val mapper by lazy { DaggerGSONMapper.builder().build().mapper}

So I created a component AndroidBuildConfigComponent

 @Component(
        modules = [
            AndroidModule::class
        ]
    )
    @Singleton
    interface AndroidBuildConfigComponent {
    
        val provider: BuildConfigProvider
    
    }

I added this code to the extension function class file:

private val configProvider by lazy { DaggerAndroidBuildConfigComponent.builder()
                                    .androidModule(AndroidModule(this)).build().provider }

However, this is underlined in red with a message

this is not defined in the current context

Is there any way I can get the application context in the extension function class to build the component?

Or more generally, is there a way to get information from AndroidBuildConfigProvider into the extension function?

I found this article that talks about Coroutines but was unable to really understand the brass tacks.

Code for Extension Class (TrackerExt.kt) for the third-party Tracker class.

private val configProvider by lazy { DaggerAndroidBuildConfigComponent.builder()
                                    .androidModule(AndroidModule(this)).build().provider }
// Above has a compile error on `this`

fun Tracker.trackEvent(name: String) {
   Log.d("Name", name)
   Log.d("Version", configProvider.version)
}
user1114
  • 1,071
  • 2
  • 15
  • 33

0 Answers0