Last active
May 20, 2020 01:12
-
-
Save go-cristian/d1660814c06f350a6eadc8ecd27237f5 to your computer and use it in GitHub Desktop.
This file contains 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
import kotlin.reflect.KClass | |
fun main() { | |
start { | |
factory<Client>{ FakeClient() } | |
factory<Service>{ FakeService(get()) } | |
} | |
val service: Service by inject() | |
service.call() | |
} | |
typealias AppDeclaration = Container.() -> Unit | |
object ContextHandler { | |
var container: Container? = null | |
fun register(container: Container) { | |
this.container = container | |
} | |
fun get() = container | |
} | |
fun start(declaration: AppDeclaration) { | |
val container = Container() | |
ContextHandler.register(container) | |
declaration.invoke(container) | |
} | |
typealias Definition<T> = () -> T | |
class Container { | |
val definitions = HashMap<KClass<*>, Definition<*>>() | |
inline fun <reified T> factory(noinline value: Definition<T>) { | |
definitions[T::class] = value | |
} | |
inline fun <reified T> get() = definitions[T::class]?.invoke() as T | |
} | |
inline fun <reified T> inject(): Lazy<T> = lazy(LazyThreadSafetyMode.NONE) { | |
val container = ContextHandler.get() | |
container?.get<T>()!! | |
} | |
////////////////// General App | |
interface Service { | |
fun call() | |
} | |
interface Client { | |
fun request() | |
} | |
class FakeService(val client: Client): Service { | |
override fun call() { | |
println("Calling the service") | |
client.request() | |
} | |
} | |
class FakeClient: Client { | |
override fun request() { | |
println("doing the request") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment