I have a class and another that inherits from it. There are some methods that I defined in the parent class that I'd like to share privately with the subclass, but not with the world.
How can I achieve something like the protected scope in other programming languages for such methods?
I've thought about introducing a role with private methods, but I'd also need to maintain some private states for use by the methods, and I would need to make both classes does
the role, but that seems to result in the instance variables (of the role) being duplicated in both classes...
There are two steps do what you want to do. The first is to have the parent class trusts
the child class:
class Dog { ... } # forward declaration necessary
class Animal {
trusts Dog; # Dog now has access to private methods
method !secret {
return 42
}
}
class Dog is Animal {
method tell-secret { ... }
}
Now, let's have the Dog reveal Animal's secret. You might think that it's simple
method tell-secret {
say self!secret
}
But that doesn't work. While calling public methods will follow standard MRO to determine the one that's called, with private ones we must be explicit. In this case, self!secret
would refer to a method !secret
directly belonging to Dog
. To refer to Animal
's secret method, we make it explicit:
method tell-secret {
say self!Animal::secret
}
And now Dog can spill the beans, so to speak.
One thing you'll notice is that once a class trusts another, it opens itself up entirely. There's no way to limit trust to individual methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With