Last active
October 13, 2022 15:24
-
-
Save klukwist/5cdb1d345f6a3b30399ea7fec3923917 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
@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