Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve the single instance API #3

Merged
merged 1 commit into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion kinject-core/src/commonMain/kotlin/kinject/ObjectGraph.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,13 @@ class ObjectGraph private constructor(
)
}

inline fun <reified T : Any> singleton(instance: T) {
singleton(instance = instance, bindType = T::class)
}

fun <T : Any> singleton(
instance: T,
bindType: KClass<*> = instance::class,
bindType: KClass<T>,
) {
val bindingKey = bindType.className
addBinding(
Expand Down
20 changes: 19 additions & 1 deletion kinject-core/src/commonTest/kotlin/kinject/ObjectGraphTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,27 @@ class ObjectGraphTest {
graph.get<CyclicalA>()
}
}

@Test
fun objectGraph_singletonInstanceInheritance_AbleToViewAsParent() {
val aa = AA()

val graph = objectGraph {
singleton<A>(aa)
}

val a: A = graph.get()
assertSame(aa, a)

assertFailsWith<KinjectException> {
graph.get<AA>()
}
}
}

class A
open class A

class AA : A()

class B(val a: A)

Expand Down