Emine Sa
Emine Sa

Reputation: 76

What is the difference between using Bind to create abstract classes and Provider to define object classes in Hilt?

When using Hilt, I notice that classes created with the @Bind annotation need to be defined as abstract, whereas classes created with the @Provides annotation are defined as objects. What are the differences between these two methods, and when should each be used?

for example:

@Module
@InstallIn(ViewModelComponent::class) // the dependencies are passed to viewmodel
abstract class SettingsDi {

    @Binds // passing implementation of the class, which inherits the interface
    fun provideAppSettings(appSettings: SettingsRepoImp): SettingsRepo

}

@Module
@InstallIn(ViewModelComponent::class)
object MailDi {

    @Provides // the instance needs to be initialized by providing context
    fun provideEmailClient(@ApplicationContext context: Context): MailClient =
        MailClientImp(context)

}

Upvotes: 1

Views: 41

Answers (1)

Subhan
Subhan

Reputation: 71

In Hilt, @Binds and @Provides serve different purposes for dependency injection:

1.  @Binds: Used for binding an implementation to an interface or abstract class. The method in a @Binds annotated abstract class (@Module) returns the interface or abstract class, and its parameter is the implementation. The class must be abstract because the method only provides the binding, not the instance creation.

Example:

@Binds
abstract fun bindRepo(impl: RepoImpl): Repo


2.  @Provides: Used to create and provide an instance of a class. The method annotated with @Provides in an object class (@Module) returns the instance. This is used when the class requires some initialization logic.

Example:

@Provides
fun provideMailClient(context: Context): MailClient = MailClientImpl(context)

When to use each:

•   Use @Binds when you have an interface or abstract class and its concrete implementation.
•   Use @Provides when you need to provide an instance that requires specific construction logic, such as using constructor parameters.

Upvotes: 0

Related Questions