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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay