What would `this` point to in such a method?
# language-proposals
d
What would
this
point to in such a method?
b
this
would be the same as in a regular companion object
d
Except there is no such companion object.
Project A adds:
fun JavaClass.Companion.foo()
- Compiler has to generate companion object. Project B adds:
fun JavaClass.Companion.bar()
- Compiler has to generate companion object. If you then bring the projects together, you have two different companion objects...?
b
If Project A and Project B never interact, that’s not an issue. Otherwise, the compiler can check if one has already been created and use that, no matter whether it’s inside the original declaration or by some extension function.
k
But where is this reference kept? The projects don't really have a common ground.
b
I'd say the first project where it's made. There must be a hierarchy of dependencies at some point, right?
k
Well, there's no fixed loading order at runtime. Classes are lazily loaded by the JVM.
b
I meant in the compiler
k
Consider the case of a Java project depending on two Kotlin libraries, each adding a companion object to
String
.
b
I mean, you'd get the same problem by subclassing. If both projects A and B create the same subclass with the same name, you differentiate by the package. Otherwise, you're out of luck and should be choosing your libraries more deliberately
k
Right but companion objects are something that's guaranteed to only have a single instance, and "adds a fake companion object for `String`" would be a strange/difficult to deal with specification for a library.
b
Anyway, this is another reason I think it was a bad decision to use companion objects instead of statics. Statics make this whole thing easier. Maybe the actual companion object these extensions reference would only be in memory? And then there wouldn't be any bytecode-level problems?
k
Memory is still a problem, what if the libraries leak the instance and try to put them in collections etc. I realize I'm presenting rediculous cases here but once you've found some leaks the whole concept breaks down.
b
Why would it leak? And finding the problematic edge cases with proposals is the whole point of this chat :P
k
Well if one of the libs stores a reference to their companion object in some shared space (eg. a collection somewhere) and the other accesses it that's a leak.
Because the other lib has it's own companion object that belongs to the same class.
b
That sounds like the kind of low-level headache that I’m bad at solving, but compiler engineers can do. In my head, this is something that should be doable, and it would bring a lot of value to the language, despite these hurdles.
k
Let's hope there's a solution!
1