Vasiliy
Vasiliy

Reputation: 16268

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?

Upvotes: 2

Views: 798

Answers (1)

Mahdi Nouri
Mahdi Nouri

Reputation: 1389

This should do it:

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

Upvotes: 8

Related Questions