If I define a function in an `inner class` I can a...
# stdlib
m
If I define a function in an
inner class
I can access it normally from outside of that class and containing class. But if I move that function out of inner class (but still inside the containing class) and make it an extension fun of the inner class, then I cannot access it in the same way - instead I need to do
with(instanceOfContainingClass)
Why the difference?
m
Member function of an inner class could be invoked on its instances. While extension member function could be invoked on containing class (outer) and receiver (inner) at the same time. By the way, there's nothing related to stdlib here.
👍 1
m
I was thinking the extension function would behave as if I had defined the function inside the inner class. Is this by design or a compiler limitation? I would have expected the compiler to be able to compile that function into the inner class so it can be used in exactly the same way. That way I, as a developer, get the benefit of keeping my inner class simple, by declaring extension functions so that they can be used transparently.
m
to compile that function into the inner class
Extensions do not work that way! The are compiled exactly into the same place where they are declared.
m
I’m not saying extensions work that way. I’m saying isn’t that how extension functions are advertised? For example, you can pull a function out of a class (having access to all non-private instances) and make it an extension function of that class, with the result being that the caller has equivalent access to that function?
m
That's right, you still can do this, but extension must be pulled to the top level to be not a member of any class.
m
Is this by design or a compiler limitation?
Also, if you pull it to the top level, then you don’t have access to the private members of the containing class.
m
By design: you can declare an extension anywhere, and it could be a member, too. Of course, as the method stops being member, it loses access to privates.
m
So there is no way to declare such an extension function in a way that the caller does not need to be changed? That sounds like a limitation of the advertised function of extensions.
m
What?
m
How to declare such an extension function in a way that the caller does not need to be changed?
m
What is 'the caller'? Call-site code? To be changed comparing to what?
m
I’m sorry, I really don’t know how to explain this any clearer.
m
Well, to sum up: top-level extension functions called the same way as member functions (but also need to be imported), but cannot see privates. Member extension functions exist, but they are kinda weird and have some restrictions.
🙏 1