On Mon, Jun 01, 2020 at 01:38:48PM -0700, ToddAndMargo via perl6-users wrote:
> On 2020-06-01 02:21, Peter Pentchev wrote:
> > class Thing {
> >     multi method do-things(Int:D $value) {
> >             say "A thing can do things with an integer: $value";
> >     }
> > 
> >     multi method do-things(Rational:D $value) {
> >             say "A thing can do things with a rational number: $value";
> >     }
> > }
> 
> Hi Peter,
> 
> I have asked this question before.  Is it possible for
> me to create my own methods.  The answer came back as
> "no".
> 
> Did you just demonstrate for me how to create my own
> methods?

Is it possible that you asked whether you could add your own methods to
an already-existing class, like add a "meows()" method to the Str class
that would return the number of occurrences of the substring "meow"?
Because in that case the answer is "in most cases, no, except for some
weirdness that may lead to weird things if it is used in weird ways".

You *can* define your *own* classes and once you define a class, it is
kind of assumed that you will define methods for that class. There is
something like a tutorial (not a reference) at
https://docs.raku.org/language/classtut (note that it starts with
an example that may not be easy to understand right off the bat, but
then in the "Starting with class" section and onwards it explains what
was used in that example point by point).

You can also extend other classes, especially ones that you have
defined. Now there are exceptions: there are some system classes that it
is not easy to extend except using some of the weirdness that
I mentioned in the first paragraph, and I really will not go into that
here.

You can also add roles to most classes using the "does" and "but"
keywords. This is explained in more detail at
https://docs.raku.org/language/typesystem#role but bear in mind that
adding roles to existing classes may cause some already-written code to
behave in unexpected ways and cause difficult-to-find mistakes, so it's
better to either add a role to a specific object or to define a new
class that says "I'm just like that original class, but I also have that
role". Of course, there are always exceptions; there are a few cases
when the so-called "monkey-patching" technique may be put to good use,
and Raku will allow you to that if you really want to, but it really
often leads to difficult-to-find mistakes.

G'luck,
Peter

-- 
Peter Pentchev  r...@ringlet.net r...@debian.org p...@storpool.com
PGP key:        http://people.FreeBSD.org/~roam/roam.key.asc
Key fingerprint 2EE7 A7A5 17FC 124C F115  C354 651E EFB0 2527 DF13

Attachment: signature.asc
Description: PGP signature

Reply via email to