Skip to content

Commit

Permalink
support declare a component definition with primary type (#773)
Browse files Browse the repository at this point in the history
* support declare a component definition with primary type

* use inline reified to support declare a component definition with primary type

Co-authored-by: shen.xudong <shen.xudong@immomo.com>
  • Loading branch information
Xudong Shen and shen.xudong authored May 29, 2020
1 parent da6c19e commit 51f9cd8
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ object Definitions {
)
}

internal fun createSingle(
fun createSingle(
clazz: KClass<*>,
qualifier: Qualifier? = null,
definition: Definition<*>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ data class Scope(
* @param secondaryTypes List of secondary bound types
* @param override Allows to override a previous declaration of the same type (default to false).
*/
fun <T : Any> declare(
inline fun <reified T : Any> declare(
instance: T,
qualifier: Qualifier? = null,
secondaryTypes: List<KClass<*>>? = null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ class ScopeDefinition(val qualifier: Qualifier, val isRoot: Boolean = false, pri

internal fun size() = definitions.size

fun <T : Any> saveNewDefinition(
inline fun <reified T : Any> saveNewDefinition(
instance: T,
qualifier: Qualifier? = null,
secondaryTypes: List<KClass<*>>? = null,
override: Boolean = false
): BeanDefinition<out Any?> {
val clazz = instance::class
val clazz = T::class
val found: BeanDefinition<*>? =
definitions.firstOrNull { def -> def.`is`(clazz, qualifier, this) }
if (found != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,25 @@ class DeclareInstanceTest {
assertEquals(a, session1.get<Simple.ComponentB>().a)
}

@Test
fun `can declare a scoped on the fly with primary type`() {

val koin = koinApplication {
printLogger()
modules(module {
scope(named("Session")) {
}
})
}.koin

val a = Simple.Component2()

val session1 = koin.createScope("session1", named("Session"))

session1.declare<Simple.ComponentInterface1>(a, named("another_a"))
assertEquals(a, session1.get<Simple.ComponentInterface1>(named("another_a")))
}

@Test
fun `can't declare a scoped-single on the fly`() {

Expand Down

0 comments on commit 51f9cd8

Please sign in to comment.