koin
koin copied to clipboard
Why it's not always possible to use constructor DSL to declare a bean just by its interface?
Constructor DSL (singleOf
, factoryOf
) operates on refied types but in some cases it doesn't work as expected. Consider the following code:
class A
interface I1
class B : I1
interface I2
class C(a: A): I2
interface I3
class D(i: I1): I3
val module = module {
singleOf(::A) // OK, injected as A
singleOf<I1>(::B) // OK, injected as I1
singleOf<I2>(::C) // ERROR: None of the following functions can be called with the arguments supplied.
singleOf<I3>(::D) // ERROR: None of the following functions can be called with the arguments supplied.
}
As soon as the constructor has any parameter, Kotlin compiler cannot match a proper version of singleOf
or factoryOf
. I know I can define injections as:
singleOf(::C) { bind<I2>() }
but the result is that there will be two injections available: C
and I2
(and it's not as clean as I would like it to be 😉).
P.S.: I'm using Koin 3.4.0.
effectively, you can't use a reified type to infer the given type directly. The idea of the Ctor DSL is to point to a function or a constructor to build an instance. In the way the API is written, it seems to let you write singleOf<I1>(::B)
, but I'm afraid it's a case to confirm with the kotlin team after that.
For now, consider using explicit bind
Thank you for the explanation. So if I understand correctly, it basically pins down to the fact that I'm trying to use the Constructor DSL not according to its intended usage and just accidentally singleOf<I1>(::B)
happens to work as I was expecting?
yes 👍 kindof IDE/Kotlin magic
Hello, I think is not an IDE/Kotlin magic, it's just that your B class has no parameter so you can specify the infered type
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.