I was thinking about something of Kotlin's inner w...
# announcements
m
I was thinking about something of Kotlin's inner workings, but reached a question: Shouldn't a Delegate follow the changes in the variable that defines how he delegates to? It seems that a Delegate Class always forwards to the same instance that it was created with. But it opens a possible misunderstanding: If I declare the delegated instance in the constructor as a var, shouldn't it change behaviour when the var changes? Or shouldn't a delegated instance always be a val, so it can't be changed? I think I prefer the first, as it would give the user more choice. Anyway, I did a Gist to exemplify the problem: https://gist.github.com/Megamiun/778234b1bb7c9bf3e9fceb6f25264ecd
k
Actually delegating to a variable rather than to an object conflicts with other semantics in the language. In
var a = foo(b)
,
a
doesn't change as
b
changes. Also when delegating to an exapression that's not just a reference wouldn't work:
class Child: Base by buildBase(...)
.
m
@karelpeeters Well, I understand the concern, but the case I showed is something that the language allows and I think should be clarified. About the
Copy code
class Child: Base by buildBase(...)
, it would continue to be like the buildBase being a val. The question I am more worried is when the syntax makes you think it will follow the variable value, as in the gist, where a
Copy code
class DelegatedContextWrapper(private var context: Context = BasicContext()) : Context by context
was allowed to be created but the delegation doesn't follow the variable.
a
This was reported way back in 2014. https://youtrack.jetbrains.com/issue/KT-5870
m
@Andreas Sinz Oh, interesting. In the meantime, it wouldn't be interesting to at least create as inspection/intention to this?
Thinking of creating one issue for this on YouTrack
k
I don't think it's a good idea to make the delegate follow changes to the delegate variable, that would pretty much be pass-by-reference, something that doesn't happen anywhere else.
m
@karelpeeters Hm... Well, I think it makes sense as the user defined it as a var. Maybe if it was limited to val, but with var as a option I see a lot of potential to confusion(And I don't think we could just remove support for that, so to me it seems that the best solution would be implementing). Even so, I asked about that on the issue @Andreas Sinz posted about the idea of at least creating a inspection/intention on the IDE and a compiler warning to advise users that it doesn't work as would be expected, so at least the users would be warned about this unexpected behaviour.