I often run into this delegation case that doesn't...
# language-proposals
d
I often run into this delegation case that doesn't compile:
Copy code
class Foo: Bar by bar {
    val bar: Bar = ...
}
This would get
Unresolved reference: bar
. Is there any reasoning for this other than the order in which the compiler is evaluating symbols? Could the compiler be improved so that it understands that
bar
exists, and generates the proper delegation code?
Copy code
override fun doBar() = bar.doBar()
I'd also like to see the ability to delegate by method instead of by entire interface, something like:
Copy code
override fun doBar() by bar
with specifying the arguments being optional, otherwise all possible overloads are delegated.
âž• 5
d
Indeed, thanks! I see you've had an even more pressing use case than mine! That it still exists after 11 years is a bit concerning, I guess it's a manner of patience at this point.
u
what are the limitations of adding
val bar
as constructor parameter with default value?
Copy code
interface Bar

object BarInstance: Bar

class Foo private constructor(val bar: Bar = BarInstance) : Bar by bar
Or to a private constructor making only a secondary constructor without `bar`public?
Copy code
interface Bar

object BarInstance: Bar

class Foo private constructor(val bar: Bar) : Bar by bar {
    constructor() : this(bar = BarInstance)
}
It is not beautiful and you’d have to add all vals that bar depends on in the same way.
r
In my use case, the instance to which the delegating class should delegate needs to be calculated every time it does the delegation.
u
i see. that seems to be one more level of abstraction then the original feature provides for. You can have a var
barFactory:: ()->Bar
and delegate to
barFactory()
. But
barFactory
is only evaluated once at initialization time.
r
Yes, that’s why I pointed the OP at an open feature request on YouTrack.