https://kotlinlang.org logo
#dagger
Title
# dagger
c

Colton Idle

08/14/2021, 5:53 PM
I'm looking at the hilt cheat sheet, and I haven't had to add @Binds to a project yet. What's the use case for it? I have plenty of places in my code where I do:
Copy code
@Provides
fun provideSomething(
    @ApplicationContext context: Context
): SomethingInterface {
    return SomethingActualImpl(context)
}
j

Javier

08/14/2021, 6:31 PM
it should be a binds
just add a new parameter to the fun with the impl as a type
c

Colton Idle

08/14/2021, 6:33 PM
But... it works without binds?
j

Javier

08/14/2021, 7:43 PM
Yes, but binds is more efficient and semantically it is easier to know that a binds is when you are binding an interface with an implementation, and provides for rest.
👍 1
a

Arun

08/16/2021, 12:21 PM
Binds is better since it is used only at compile time to link implementation to interface. The module itself is not used in Dagger generated code, as dagger would generate the code for linking the two. This means the module class can be fully removed by R8/Proguard on release builds. When provides is used, Dagger generates code that will actually call the method you defined since it can't know what you are doing inside the method.
c

Colton Idle

08/16/2021, 1:51 PM
That's super helpful. Thanks @Arun
p

pollux-

08/16/2021, 8:31 PM
j

Jeremy

08/16/2021, 11:03 PM
Is there practical difference between
@Binds
and static
@Provides
?
t

trevjones

08/17/2021, 5:06 PM
if you are using provides when a binds would work you run the chance of having people basically copy pasting the entire constructor arg list over. That can cause some pretty sad signal to noise ratio's for code reviewers.
not always true, but that is exactly what is happening in colton's OP
j

Jeremy

08/17/2021, 5:54 PM
I agree.
@Binds
forces dependencies to be public to other modules so sometimes its a tradeoff
2 Views