Hi, is it possible to resolve generic types with k...
# koin
h
Hi, is it possible to resolve generic types with koin? I've tried with
Copy code
import org.koin.core.KoinComponent
import org.koin.core.context.startKoin
import org.koin.dsl.module

class State<T>(val initialValue: T, name: String? = null)

fun main() {
    val sim = module(createdAtStart = true) {

        single{ State("red") }
        single{ State(false) }
    }

    startKoin() { modules(sim) }

    val koin = (object : KoinComponent {}).getKoin()
    val boolState = koin.get<State<Boolean>>()
    val stringState = koin.get<State<Boolean>>()
}
but this fails with
Copy code
Exception in thread "main" org.koin.core.error.DefinitionOverrideException: Definition '[Single:'State']' try to override existing definition. Please use override option or check for definition '[Single:'State']'
t
It's not possible directly. Koin uses
KClass
as key and thus looses the generic parameter types.
I worked around it by defining extensions using
typeOf
to create a custom
Qualifier
with this type:
TypeQualifier(KType,Qualifier)
h
Thanks for sharing your insights @tynn. Could you provide an example to illustrate how
typeOf
can be used here?
t
Sure... The qualifier type should look similar to this one...
Copy code
data class TypedQualifier(
  private val type: KType,
  private val qualifier: Qualifier,
) : Qualifier {
  override val value = "$type:${qualifier.value}"
}
Then just override the DSL to support it...
Copy code
inline fun <reified T> inject2<T>(
  qualifier: Qualifier,
  ...,
) = inject<T>(
  TypedQualifier(typeOf<T>(), qualifier),
  ...,
)
h
How does this differ from the existing TypeQualifier in the koin API? With that we can doe already
Copy code
single(TypeQualifier(Boolean::class)){ State<String>("red") }
t
TypeQualifier
uses
KClass<T>
while the implementation above uses
KType
which doesn't loose the generic types.
d
kodein lib can handle types. they use some reflection magic to retrieve a type
h
Indeed & thanks @deviant this is possible with kodein. Since it seems to be an implementation issue, I've created https://github.com/InsertKoinIO/koin/issues/976
👍 1
197 Views