I currently have this `class Bar @Inject construc...
# dagger
c
I currently have this
class Bar @Inject constructor (random: Thing)
and I don't need a provides method (except for
Thing)
. Everything is good. Now whats the best way to make Bar an interface?
interface Bar
class ConcreteBar @Inject constructor (randomButOnlyNeededForConcreteImpl: Thing): Bar
I have this provides statement, and it works... but kinda annoying to repeat the injection params since I am already doing it at the class with the @Inject annotation. Am I doing something wrong?
Copy code
@Provides
@Singleton
fun provideBar(
randomButOnlyNeededForConcreteImpl: Thing)
): Bar {
  return ConcreteBar(randomButOnlyNeededForConcreteImpl)
}
n
`@Binds` is your friend here!
Copy code
@Module
@InstallIn(SingletonComponent::class)
interface MyBindsModule {
    @Binds
    fun bindsBar(impl: ConcreteBar): Bar
}
Annotate
ConcreteBar
directly with
@Singleton
instead of putting it on the provides or binds method
I can't link to specific parts of the Dagger site but look under `Satisfying Dependencies" here
c
thanks!
so much better
1
the fact that the Module has to be an interface is kinda weird, but better than what i had
Also. just for fun. i tried without singleton at all and I crashed because in my example I'm actually injecting DataStore.
Copy code
java.lang.IllegalStateException: There are multiple DataStores active for the same file: preferences.preferences_pb. You should either maintain your DataStore as a singleton or confirm that there is no two DataStore's active on the same file (by confirming that the scope is cancelled).
if I put the Singleton on either the binds or the @inject... they both work
¯\_(ツ)_/¯
n
Both work it's just a personal preference to keep it with the concrete implementation instead of whatever code you need to write to satisfy dagger somewhere else. ideally you should just be able to look at the
ConcreteBar
file and know it's a singleton without having to look at another file, does that make sense?
👍 1
c
thanks! all of this was extremely helpful! getting into the habit of writing more tests and so i have to revisit some of my dagger skills. lol
👍 1
re-read that doc today. seems like a version of that in 2023 updated to kotlin would be nice. specifically the section about using
static
and how that actually translates
n
If you're using a recent version of Dagger you just need to make your modules with
@Provides
methods
objects
and Dagger will optimize it correctly.
c
i guess i can do the interface for @ binds, and companion object with @ provides (like suggested in the below thread) and everything should be good then!
👌 2