Use Dagger's @Provides annotation on Kotlin propery

Viewed 511

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?

1 Answers

This should do it:

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