在 doc.perl6.org 中,我见过很多这样的方法:
method sum(List:D: --> Numeric:D)
我知道List:D
是一种定义的列表类型,但是D
后面的冒号是什么意思(即List:D:
中的第二个(?
我在 S12 对象中找到了一些解释:
=head2 调用方
调用的声明是可选的。 您可以随时访问 使用关键字
self
的当前调用。 ... 要标记显式调用,只需在其后加上冒号:method doit ($x: $a, $b, $c) { ... }
但我不明白,乍一看有点奇怪。
默认情况下,方法的调用为self
因此,这两者都是等效的:
method foo ( $a ){…}
method foo ( self: $a ){…} # generates warning
因此,将第一个示例扩展到它的缩写
method sum( List:D self: --> Numeric:D ){…} # generates warning
基本上,如果你想为方法指定 invocant(第一个参数(的类型,但只想使用self
而不是指定一个新变量,你可以这样写它。
它使用:
将调用与其他参数分开的原因是为了简化未指定调用或调用类型的常见情况。
当您使用基本类型约束定义 sub 时,如下所示:
sub testB (Str $b) { say $b; }
然后,您可以使用相关类型的实际实例以及类型对象本身来调用它:
> testB("woo")
woo
> testB(Str)
(Str)
:D是一个额外的类型约束,因此您只能传递"已定义"的实例:
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
更多细节可以在这里找到