koin: Failure to resolve lists (generics)
Describe the bug If you register two lists and then resolve one inside a bean, the list contains elements of the wrong type. Probably not just limited to lists, but other generics.
To Reproduce
import org.junit.Test
import org.koin.KoinContext
import org.koin.dsl.module.applicationContext
import org.koin.standalone.StandAloneContext
import kotlin.reflect.KClass
class Type1
class Type2
class Type3(val list: List<Type1>)
class ListsTest {
@Test
fun `list resolution failure`() {
val type1Element = Type1()
StandAloneContext.startKoin(
listOf(
applicationContext {
bean { listOf(type1Element) }
},
applicationContext {
bean { listOf(Type2()) }
},
applicationContext {
bean {
Type3(get())
}
}
)
)
(StandAloneContext.koinContext as KoinContext).get<Type3>().list `should equal` listOf(type1Element)
}
}
java.lang.AssertionError:
Expected :[Type1@77b52d12]
Actual :[Type2@2d554825]
And if you try to use the contents of the list, you will get a class cast error.
(StandAloneContext.koinContext as KoinContext).get<Type3>().list.forEach { }
->
java.lang.ClassCastException: Type2 cannot be cast to Type1
Expected behavior
Type3 instance should have been resolved with the list of Type1 that was registered.
Koin project used and used version (please complete the following information):
koin-core version 0.9.3
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 18 (9 by maintainers)
Ok, sorry.
I rewrite your initial test with Koin 1.0:
I got an
BeanOverrideExceptionat start. Then, it’s protected against that case.Then to fix it, the name workaround as you mentioned:
I can add it to the documentation/quick refs to help people on such subject.
The name work around in full.
Hello,
generics data are not kept in Koin definition metadata. Using directly the List type won’t work.
Also annother to retrieve the right instance, is to name it:
and then request it with
get<ArrayList>(name = "ints")