What does the second colon in "List:D:" mean in Perl 6?

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

Tags:

Raku