Skip to content

Dagger ‐ When to use @provides and when to use @binds

Devrath edited this page Oct 8, 2023 · 2 revisions

Observations

  • From the code written there is not much change but change exists in the generated code basically the number of lines in factory classes
  • If you have just a few modules it does not matter but if you have thousands of modules the no of lines that are generated does matter
  • Usually we use @binds when an interface comes into play and we are returning an interface and the implementation we pass in the parameter of the function in the module class function also here we need to note the implementation class must have a @Inject annotation added to it other-wise the dagger will not know how to create an object for the implementation.

Implementations

Connection.kt

interface Connection {
    fun connect(endpoint:String)
}

HttpConnection.kt

class HttpConnection @Inject constructor() : Connection {
    override fun connect(endpoint: String) {
        PrintUtils.printLog("HttpConnection made")
    }
}

Components

ConnectionComponent.kt

@Component(modules = [HttpsConnectionModule::class])
interface ConnectionComponent {
    fun provideHttpsConnection() : HttpsConnection
}

Example for @Module

@Module
@DisableInstallInCheck
class HttpConnectionModule {
    @Provides
    fun provideHttpConnection() : Connection {
        return HttpConnection()
    }
}

Example for @binds

@Module
@DisableInstallInCheck
abstract class HttpConnectionModule {
    @Binds
    abstract fun provideHttpConnection(connection: HttpConnection) : Connection
}

Pictorial representation

Untitled

Clone this wiki locally