Proposal: self keyword #2618
Unanswered
p-lindberg
asked this question in
Language Ideas
Replies: 3 comments
-
Wouldn't this break encapsulation? |
Beta Was this translation helpful? Give feedback.
0 replies
-
I don't see how it would. Could you clarify? |
Beta Was this translation helpful? Give feedback.
0 replies
-
Check out #252 and #902. Although they're different in that they reuse the existing |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I propose that the following:
is given the following shorthand syntax:
In short, the self return type keyword makes a member method automatically return its own instance.
This would not just be syntactic sugar, but would also function as a guarantee that a method returning its own type does not in fact return another instance of the same type. This way, callers can be certain they are dealing with the same instance after calling such a method. This would be useful when building frameworks that employ method chaining.
Inheritance would need to be considered. I think the most natural course of action would be to let self-returning methods on derived types return a reference of the derived type, and not the base type. This would provide additional convenience in situations where you perform method chaining on derived objects: you would still be accessing an object of derived type after the first method invocation, which means that you don't have to downcast after calling a base method. Example:
This would be consumed as follows:
currently, this would look like:
chaining these methods requires a cast:
Beta Was this translation helpful? Give feedback.
All reactions