In the doc.perl6.org, i've seen many methods like this:
method sum(List:D: --> Numeric:D)
I konw List:D
is a type of List that is defined, but what does the colon after the D
mean (i.e. the second one in List:D:
)?
I found some explain in S12-objects:
=head2 Invocants
Declaration of the invocant is optional. You may always access the current invocant using the keyword
self
. ... To mark an explicit invocant, just put a colon after it:method doit ($x: $a, $b, $c) { ... }
but I don't understand, it's somewhat strange at first glance.
By default methods have an invocant of self
So both of these would be equivalent:
method foo ( $a ){…}
method foo ( \self: $a ){…} # generates warning
So expanding the first example out to what it is sort-of short for
method sum( List:D \self: --> Numeric:D ){…} # generates warning
Basically you write it that way if you want to specify the type of the invocant (first argument) to a method, but just want to use self
rather than specify a new variable.
The reason it uses the :
to split up the invocant from the rest of the parameters is to simplify the common case where you don't specify the invocant, or type of the invocant.
When you define a sub with a basic type constraint like this:
sub testB (Str $b) { say $b; }
then you can call it with an actual instance of the type in question as well as with the type object itself:
> testB("woo")
woo
> testB(Str)
(Str)
The :D is an additional type constraint, so you can only pass a "defined" instance:
sub testC (Str:D $c) { say $c; }
> testB(Str)
(Str)
> testC("hoo")
hoo
> testC(Str)
Parameter '$c' of routine 'testC' must be an object instance of type 'Str', not a type object of type 'Str'. Did you forget a '.new'?
in sub testC at <unknown file> line 1
in block <unit> at <unknown file> line 1
More details can be found here
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