Hilt – inject dependency from app to module

  android, dagger-hilt, kotlin

Lets say I have Android app project with one main "app" module and one "module1" module. "app" has dependency on "module1"

implementation project(":module1")

I’m starting to use Hilt to inject dependency from "app" to "module1".

In "module1" I define interface

interface TestInterface {
    fun doSomething()
}

which I implement in "app"

class Test: TestInterface {
    override fun doSomething() {
        Log.i("Test", "Something")
    }
}

Now, I want to inject "Test" implementation into "module1" and use it.
I created test class:

class Work {

    @Inject
    lateinit var test: TestInterface

    fun doWork() {
        test.doSomething()
    }

}

Which I try to use in MainActivty

Work().doWork()

But it does not work.

kotlin.UninitializedPropertyAccessException: lateinit property test has not been initialized
    at module1.Work.getTest(Work.kt:8)
    at module1.Work.doWork(Work.kt:11)

I’ve set:

@AndroidEntryPoint
class MainActivity

and

@HiltAndroidApp
class HiltApplication

Hilt module:

@Module
@InstallIn(SingletonComponent::class)
interface Dependencies {
    @Binds
    fun bindsTestInterface(test: Test): TestInterface
}

Any idea why this does not work?

Source: Android Questions

LEAVE A COMMENT