--> Constraining Return Types
Documentation for --> Constraining Return Types, assembled from the following types:
There are multiple ways to constrain return types on a sub or method. All versions below are currently valid and will force a type check on successful execution of a routine.
sub foo(--> Int) ;say foo.perl; # OUTPUT: «Nil␤»
Type captures are not supported.
This form is preferred for several reasons: (1) it can handle constant values while the others can't; (2) for consistency, it is the only form accepted on this site;
The return type arrow has to be placed at the end of the parameter list, with or without a
, before it.
sub greeting1(Str --> Str) # Validsub greeting2(Str , --> Str) # Validsub favorite-number1(--> 42) # OUTPUT: 42sub favorite-number2(--> 42) # OUTPUT: 42
If the type constraint is a constant expression, it is used as the return value of the routine. Any return statement in that routine has to be argumentless.
sub foo(Str --> 123)my = foo("hello"); # OUTPUT: hellosay ; # OUTPUT: 123
# The code below will not compilesub foo(Str --> 123)my = foo("hello");say ;
returns following a signature declaration has the same function as
--> with two caveats.
(1) This form is planned for future removal. (2) This form does not work with constant values
sub greeting(Str ) returns Str # Valid
sub favorite-number returns 42 # This will fail.
of is just the real name of the
sub foo() of Int ; # Valid
sub foo() of 42 ; # This will fail.
This is similar to placing type constraints on variables like
my Type $var = 20;, except the
$var is a definition for a routine.
my Int sub bar ; # Valid
my 42 sub bad-answer ; # This will fail.