Search code examples
androidkotlindagger-2

Use Dagger's @Provides annotation on Kotlin propery


When explicitly providing services from Dagger's modules, I can use the following syntax:

@Provides
fun provideService(): MyService = MyService()

However, if I try to use property instead of a function, it doesn't work:

@Provides
val myService get() = MyService()

The error I get is: This annotation is not applicable to target 'member property without backing field or delegate'.

The approach with a property feels like it should work, but it doesn't.

My question is whether there is a way to use properties to provide services from Dagger modules?


Solution

  • This should do it:

    val myService: MyService 
        @Provides get() = MyService()