Hello, How to inject variable in kotlin extension ...
# android
a
Hello, How to inject variable in kotlin extension function? I have dependency that is provided through Hilt. I'm trying to create extension function which will use default value as this dependency.
r
do you have some gist? @aniruddha dhamal
a
@radityagumay, Here's the code snippet
Copy code
interface Car {
    fun start()
}
class CarImpl {
    fun start() {...}
}

@Module
@InstallIn(SingletonComponent::class)
object CarModule {
    @Provides
    @Singleton
    fun provideCar(context: Context): Car {
        return CarImpl(context)
    }
}
fun Context.car() {
    // How to access Car here? In extension function.
}
How do i inject/access Car here?
r
Dagger/Hilt not able to inject in that way. If you want to really make it work, you need to create another helper so to inject the dependency on ext function
a
@radityagumay, How can this be done using helper?
r
what i meant to helper is through annotation processor, and i don't it worth tho
and i believe we can use reflection based injection?
since the receiver of extension function is a Context you can cast the context to meaningful object
for example @aniruddha dhamal
Copy code
interface AppFooProvider {
      val provider: FooProvider
      interface FooProvider {
            val foo: Foo
      }
}

class MyApp : Application(), AppFooProvider {

   @Inject
   internal lateinit var foo: Foo

    override val provider: FooProvider by lazy {
        object : FooProvider {
            override val foo: Foo 
                 get() = this@MyApp.foo
        }
    }

    override fun onCreate(bundle: Bundle) {
          super.onCreate(bundle)
          DaggerAppComponent.factory()
              .create(this)
              .inject(this)
    }
}

// usage
fun Context.getFoo() : Foo {
    return (this.applicationContext as AppFooProvider).provider.foo
}
a
Thanks @radityagumay! There seems to be lot of wiring. Agree, it doesn't seems to be that worth.
👍 1