Created
April 10, 2019 14:32
-
-
Save code-twister/895f38f26c7ba5af2a7ceb0662d26079 to your computer and use it in GitHub Desktop.
TP Kotlin Injection by delegate idea
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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