beigirad
beigirad

Reputation: 5724

Is optional using @Inject for all constructors in Dagger2?

Why some people uses @Inject for constructor of classes and some other did not use this annotation for constructor. Is it optional to use this?

Upvotes: 1

Views: 246

Answers (1)

eleven
eleven

Reputation: 6847

It's not needed if you provide instance yourself:

//without @Inject
class SomeInstance contructor(...): SomeInstanceInterface{}

@Module
class Module{
  @Provides()
  fun provide():SomeInstanceInterface {
    return SomeInstance(...)
  }
}

But if you want that Dagger create instance for you, then you need to mark constructor with @Inject and ask Dagger to create instances:

@Module
class Module{
  @Provides()
  fun provide(inst: SomeInstance):SomeInstanceInterface = inst
}

or

@Component
interface Component{
  fun someInstance():SomeInstanceInterface
} 

Upvotes: 1

Related Questions