Idea: Add the ability for interface delegates to b...
# language-proposals
s
Idea: Add the ability for interface delegates to be able to delegate to class members, and not just constructor parameters (eg. you can create a private val for a class if you just want to delegate to it without having the constructor inject it)
a
What real world problem does that solve?
s
Allows you to move common functionality in multiple classes out of the classes themselves in the same way as interface delegation does, without having to create a bunch of proxy methods or have a bunch of constructor parameters.
eg.
Copy code
class Foo(): Bar by barImpl {
    val barImpl = BarImpl()
}
, which would currently throw a "Unresolved reference" compiler error since "by" isn't allowed to check fields.
Example from code I'm currently working with:
Copy code
class DiscordClient(val token: String) : EventDispatcher /* I'd like to do "by _state" here rather than have the below methods */{
    internal val _state = ClientState()

    // Implementation of EventDispatcher
    // Not using "by" here because I'd like to keep it out of the primary constructor as a default parameter
    override fun <T : DiscordEvent> listen(clazz: KClass<T>, predicate: (T) -> Boolean, removeAfterDispatch: Boolean, handler: suspend (T) -> Unit) = _state.listen(clazz, predicate, removeAfterDispatch, handler)
    override suspend fun <T : DiscordEvent> dispatch(event: T, dispatchClass: KClass<T>) = _state.dispatch(event, dispatchClass)
ClientState contains the actual machinery for EventDispatcher but that's an internal class and I'd like to expose the APIs to DiscordClient without actually implementing it in DiscordClient (since it handles other things too and would quickly become huge)
a
do you need to access
_state
inside the class?
s
Yes
a
hmm, that makes it impossible to test the class in isolation and requires some work to prohibit edge-cases, but lets see what the devs say
c
I'd like this as well, there's a YT-issue: https://youtrack.jetbrains.com/issue/KT-83