Search code examples
androiddependency-injectionkotlinkodein

Kodein using generics to bind dependencies


I tried to bind the dependencies in the following way

fun getKodeinConfigurationsGraph(context: Context, url: String) = Kodein.lazy {
    import(dataBaseModule(context))

    import(retrofitModule(url))
    bind<ConfigurationsService>() with provider { instance<RetrofitHandler>().buildCall(ConfigurationsService::class) }

    import(getConfigurationRepository<Contact>(ConfigurationDataType.CONTACT))

}

fun <T> getConfigurationRepository(type: ConfigurationDataType) =
        Kodein.Module {
            bind<BaseDao<Contact>>() with provider { instance<AppDatabase>().getContactDao() }
            bind<LocalDataSource<T>>() with provider { LocalDataSourceImpl<T>(dao = instance()) }
            bind<BaseRestHandler<List<T>>>() with provider { ConfigurationsHandler<T>(configurationsService = instance(), type = type) }
            bind<RemoteDataSource<List<T>>>() with provider { RemoteDataSourceImpl<List<T>>(restHandler = instance()) }
            bind<Repository<T>>() with provider { BasicRepository<T>(localDataSource = instance(), remoteDataSource = instance()) }
        }

But i got the following error

java.lang.IllegalArgumentException: bind<LocalDataSource<T>>() uses a type variable named T, therefore, the bound value can never be retrieved.

I wanted to import the module and get the required dependency, without needing to repeat the same binds every time.

Is there a way to do this?


Solution

  • Try changing to inline fun <reified T> getConfigurationRepository(...). Then it'll work exactly as if you did repeat the binds every time. See https://kotlinlang.org/docs/reference/inline-functions.html for documentation.

    bind itself also uses reified type parameters.