Dependency Injection with Dagger 2
Dagger codegen: @Binds, @Provides, and Modules
Up next
Previous
About
In this lesson, we go over the @Binds and @Provides annotations, and how the generated code changes depending on which one you use. They can be functionally equivalent, but knowing how Dagger handles your Module declarations is important as it can help you write Modules that will lead to more efficient generated code.
TLDR: Use @Binds whenever possible.
Instructor
Links
Comments
Hi Brandon,
I am wondering if you was to use a abstract class and @Binds annotation. Would that still generate un-needed code? As abstract class would not need to be created and would be very similiar to an interface
i.e.
@Module
abstract class HomeModule {
@Binds
@IntoMap
@ViewModelKey(HomeViewModel::class)
abstract fun bindViewModel(homeViewModel: HomeViewModel): ViewModel
}
If the code generation is the same, is there any benefit using one of the other
Hi Steve!
Yes abstract classes should lead to the same benefit. Interface support was added some time later to remove just that little bit more of boilerplate.
The one thing you can do in abstract module classes, that you can't with interface modules, is have static @Provides methods mixed with @Binds methods. In that case, the class cannot be stripped, however (I think, it has been a while since I've done that). I haven't used that strategy recently since it requires companion objects in Kotlin. If I need to have @Binds and "static" @Provides methods, I personally use separate modules. Interface for the @Binds dependencies, and an object
for the "static" provides dependencies.
Lessons in Dependency Injection with Dagger 2






















































