Skip to content

Commit

Permalink
Improve discussion and examples of programmatic use of class method n…
Browse files Browse the repository at this point in the history
…ames (#4168)

+ provide more practical examples
+ add a cross-reference link so the curious can find the discussion
  • Loading branch information
tbrowder committed Dec 28, 2022
1 parent 349986b commit 1fb5701
Showing 1 changed file with 31 additions and 10 deletions.
41 changes: 31 additions & 10 deletions doc/Language/objects.pod6
Expand Up @@ -378,15 +378,6 @@ returns:
method Str { "⤷ $!origin\n$ⲧ$.notes()$!destination ⤶\n" }
=end code
Method names can be resolved at runtime with the C<.""> operator.
=begin code
class A { has $.b };
my $name = 'b';
A.new."$name"().say;
# OUTPUT: «(Any)␤»
=end code
The syntax used to update C<$.notes> changed in this section with respect
to the previous L<#Attributes> section. Instead of an assignment:
Expand All @@ -398,10 +389,12 @@ we now do a method call:
=for code :preamble<my $trip>
$trip.notes("First steps");
X<Classes|Methods,overriding default accessors>
Overriding the default auto-generated accessor means it is no longer
available to provide a mutable container on return for an assignment.
A method call is the preferred approach to adding computation and
logic to the update of an attribute. Many modern languages can update
logic to the update of an attribute (see 'programmatic use' of such calls
in the following section). Many modern languages can update
an attribute by overloading assignment with a “setter” method. While
Raku can overload the assignment operator for this purpose with a
L<C<Proxy>|https://github.com/Raku/roast/blob/master/S12-attributes/mutators.t>
Expand All @@ -411,6 +404,34 @@ L<weaker object oriented design|https://6guts.wordpress.com/2016/11/25/perl-6-is
=head2 Class and instance methods
X<Classes|Methods,programmatic use>
Method names can be resolved at runtime with the C<.""> operator which
enables programmatic use of such names. For example, since an
attribute name is also a method, we can show attibute C<a>'s value by
calling the C<a> method:
=begin code
class A { has $.a = 9 }
my $method = 'a';
A.new."$method"().say;
# OUTPUT: «9␤»
=end code
A method with arguments may be called in a similar manner:
=begin code
class B {
has $.b = 9;
method mul($n) {
$!b * $n
}
}
my $method = 'mul';
B.new."$method"(6).say;
# OUTPUT: «54␤»
=end code
X<Classes|Methods,signatures>
A method's signature can have an I<explicit invocant> as its first parameter
followed by a colon, which allows for the method to refer to the object
it was called on.
Expand Down

0 comments on commit 1fb5701

Please sign in to comment.