kosi-libs / Kaverit

A light multiplatform Kotlin reflection API
MIT License
17 stars 1 forks source link

Binding type parameter #8

Closed nsragow closed 9 months ago

nsragow commented 9 months ago

I can't figure out a way to bind a type parameter:

class Container<Type>(val obj: Type) {
    fun typeBinder(builder: Kodein.Builder) {
        builder.apply { 
            bind() from singleton { obj }
        }
    }
}

Is this possible?

nsragow commented 9 months ago

I came up with a workaround:

class Container<Type : Any>(val obj: Type, val klass: KClass<Type>) {
    fun typeBinder(builder: Kodein.Builder) {
        builder.apply {
            val s = Singleton(
                scope,
                contextType,
                TT(klass),
                null,
                true,
            ) {
                obj
            }
            bind() from s
        }
    }
}

Not sure if this is how I am supposed to be using this though.

romainbsl commented 9 months ago

Hi, what are you trying to bind really ? (I guess that your are working with Kodein (you are on Kaverit repo here).

Kodein should have everything you need. If you are trying to bind an existing object, you can do:

class Foo

val obj = Foo()

val di = DI {
 bindInstance { obj }
}

val injectedFoo : Foo by di.instance()

assert(obj == injectedFoo)
nsragow commented 9 months ago

O sorry my bad, I'll post to the Kodein repo

romainbsl commented 9 months ago

duplicate: https://github.com/kosi-libs/Kodein/issues/449