Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define protected methods in Raku?

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...

like image 897
cowbaymoo Avatar asked Aug 13 '20 02:08

cowbaymoo


1 Answers

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.

like image 81
user0721090601 Avatar answered Nov 15 '22 21:11

user0721090601