DEV Community

Aldo Wachyudi
Aldo Wachyudi

Posted on

3 1

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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools