loading...

How to use Dagger 2 - Binds Annotation

aldok profile image Aldo Kelvianto ・1 min read

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();
    }
}

Into this:

@Module
abstract class HomeModule {

    @Binds
    abstract HomeView provideHomeView(HomeViewImpl impl);
}

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);
}

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)
        }
    }
}

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.

Discussion

pic
Editor guide