Skip to content

Instantly share code, notes, and snippets.

@code-twister
Created April 10, 2019 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-twister/895f38f26c7ba5af2a7ceb0662d26079 to your computer and use it in GitHub Desktop.
Save code-twister/895f38f26c7ba5af2a7ceb0662d26079 to your computer and use it in GitHub Desktop.
TP Kotlin Injection by delegate idea
package delegation
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
class Foo: Injectable by ScopeWrapper() {
val bar: Bar by inject()
}
class Bar
interface Injectable {
var scope: Any?
}
class ScopeWrapper: Injectable {
override var scope: Any? = null
}
fun Foo(scope: Any): Foo = Foo().apply { this.scope = scope }
val foo = Foo("jfdksjief")
//used for the `by` fields injection
class InjectionDelegate<OWNER: Injectable, T>(val obj: OWNER, val clazz: Class<T>) : ReadOnlyProperty<OWNER, T> {
override fun getValue(thisRef: OWNER, property: KProperty<*>): T {
TODO()
// obj.scope.getInstance(clazz)
}
}
//provides a delegate per field
//I actually wonder about the byte code cost in business classes
//that would use a scope as a parameter, it seems to me the cost
//of so many inline function overrides for reified types can be huge
inline fun <reified T> Injectable.inject(): InjectionDelegate<Injectable, T> {
return InjectionDelegate(this, T::class.java)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment