DEV Community 👩‍💻👨‍💻

Aldo Wachyudi
Aldo Wachyudi

Posted on

How to use Dagger 2 - Binds Annotation

Dagger 2 introduces new annotation @Binds. You can use it to simplify @Provides, it turns this:

@Module
class HomeModule {

    @Provides
    HomeView provideHomeView() {
        return new HomeViewImpl();
    }
}
Enter fullscreen mode Exit fullscreen mode

Into this:

@Module
abstract class HomeModule {

    @Binds
    abstract HomeView provideHomeView(HomeViewImpl impl);
}
Enter fullscreen mode Exit fullscreen mode

Can we use @Binds and @Provides together?

Yes, you can use static method.

@Module
public abstract class MainActivityModule {

    @Provides
    static MainPresenter provideMainPresenter(MainView mainView, ApiService apiService) {
        return new MainPresenterImpl(mainView, apiService);
    }

    @Binds
    abstract MainView provideMainView(MainActivity mainActivity);
}
Enter fullscreen mode Exit fullscreen mode

On Kotlin, you can use companion object to achieve the same thing.

@Module
abstract class MainApplicationModule {

    @Binds
    abstract fun provideApplication(application: Application): Context

    @Module
    companion object {
        @JvmStatic
        @Provides
        internal fun provideAgeMap(): Map<String, Int> {
            return mapOf("Luffy" to 17, "Shanks" to 37)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Verdict

@Binds clearly makes component declaration more succint. There is a slight problem when combining it with @Provides. While both approach works. I would prefer to still use @Provides for the sake of consistency. But you may want to experiment it yourself too feel which one you like better.

Top comments (0)

We are hiring! Do you want to be our Senior Platform Engineer? We're hiring for a Senior Platform Engineer and would love for you to apply.

Head here to learn more about who we're looking for.