Using context receivers for dependency injection, is that a valid use-case?
interface Blah {
suspend fun doSomething()
}
class BlahImpl : Blah {
context(Connection)
suspend fun doSomething() { ... }
}
currently the above doesn't compile (and the compiler actually just outputs garbage without hinting that this is not allowed - KT-58442) unless you add the context receiver on the
doSomething()
in the interface as well
interface Blah {
context(connection)
suspend fun doSomething()
}
which leads to my question, should the interface really know in what context(s) it will be used, doesn't that defeat the purpose of an interface?
the actual context in which the implementation runs sounds like implementation detail that now pollutes the interface.
maybe the same can be said for suspend, should that really be in the interface too?
that being said, if it's not in the interface, then you would be forced to specify at the call-site which implementation you are referring to which would then either require a context or no context or to call it from a coroutineScope or just normally.