Sobes.tech
Middle+

Tell me about Dagger annotations @Provides and @Binds

sobes.tech AI

Answer from AI

The @Provides annotation is used in modules to define methods that create dependency instances. These methods are marked with @Provides and return the type of dependency they supply. The method body contains the logic for creating the instance.

@Module
class AppModule {

    @Provides
    fun provideDatabase(context: Context): AppDatabase {
        // Logic for creating the database
        return Room.databaseBuilder(context, AppDatabase::class.java, "app-database").build()
    }
}

The @Binds annotation is used in modules to indicate that one interface is linked to a specific implementation. It is applied to abstract methods that take an implementation as a parameter and return an interface. Dagger generates more efficient code for @Binds compared to @Provides, as it does not require a method call to create the instance.

@Module
interface AppBindsModule {

    @Binds
    fun bindRepository(impl: DefaultRepository): Repository
}

interface Repository { /* ... */ }
class DefaultRepository @Inject constructor(): Repository { /* ... */ }

Main differences:

  • @Provides is used for creating object instances, often requiring more complex logic or dependencies.
  • @Binds is used for binding abstract types (interfaces) to their concrete implementations, which is more efficient when there is no complex creation logic.
Tell me about Dagger annotations @Provides and @Binds… - sobes.tech