Skip to content

Instantly share code, notes, and snippets.

View klukwist's full-sized avatar

Aleksei Cherniaev klukwist

View GitHub Profile
fun interface SamFoo {
fun bar() : String
}
val samFoo = SamFoo {
"hello world"
}
samFoo.bar()
interface RegularFoo {
fun bar() : String
}
val regularFoo = object : RegularFoo {
override fun bar(): String {
return "hello world"
}
}
fun module(scope: SimpleDiScope.() -> Unit) {
scope.invoke(SimpleDiScope)
}
object SimpleDiScope {
inline fun <reified T : Any> factory(factory: InstanceType.Factory<T>) {
SimpleDiStorage.addFactory(factory)
}
inline fun <reified T : Any> factoryWithParams(factory: InstanceType.ParamFactory<T>) {
SimpleDiStorage.addFactory(factory)
}
inline fun <reified T : Any> singleton(factory: InstanceType.Factory<T>) {
inline fun <reified T : Any> get(noinline params: (Params.() -> Unit)? = null): T {
return SimpleDiStorage.getInstance(params)
}
@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
}
val aInstance = get<A>() // or val aInstance: A = get()
val bInstance = get<B>()
val cInstance = get<C> {
params(bInstance)
}
interface A {
fun foo()
}
class AImpl: A {
override fun foo() {
print("A")
}
}
@klukwist
klukwist / DiStyle
Last active October 13, 2022 15:10
module {
singleton<A> { AImpl() }
factory<B> {
BImpl(
a = get()
)
}
factoryWithParams<C> { (aParam) ->
C(
a = aParam as A,
sealed interface InstanceType<T> {
fun interface Factory<T> : InstanceType<T> {
fun build(): T
}
fun interface ParamFactory<T> : InstanceType<T> {
fun build(vararg params: Any): T
class Params {
var parameters: Array<out Any> = arrayOf()