Skip to content

Instantly share code, notes, and snippets.

@klukwist
Last active October 13, 2022 15:24
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 klukwist/5cdb1d345f6a3b30399ea7fec3923917 to your computer and use it in GitHub Desktop.
Save klukwist/5cdb1d345f6a3b30399ea7fec3923917 to your computer and use it in GitHub Desktop.
@PublishedApi
internal object SimpleDiStorage {
val instances = mutableMapOf<KClass<*>, InstanceType<*>>()
inline fun <reified T : Any> addFactory(factory: InstanceType<T>) {
check(instances[T::class] == null) {
"Definition for ${T::class} already added."
}
instances[T::class] = factory
}
inline fun <reified T : Any> getInstance(noinline parameters: (Params.() -> Unit)? = null): T {
return when (val factory = instances[T::class]) {
is InstanceType.Singleton -> factory.instance as T
is InstanceType.Factory -> factory.build() as T
is InstanceType.ParamFactory -> {
val factoryParams = Params().apply(requireNotNull(parameters)).parameters
factory.build(*factoryParams) as T
}
null -> error("No factory provided for class: ${T::class.java}")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment