--> Constraining Return Types

Documentation for --> Constraining Return Types assembled from the following types:

class Signature

From Signature

(Signature) --> Constraining Return Types

There are multiple ways to constrain return types on a Routine. All versions below are currently valid and will force a type check on successful execution of a routine.

Nil and Failure are always allowed as return types, regardless of any type constraint. This allows Failure to be returned and passed on down the call chain.

sub foo(--> Int{ Nil };
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 $name  --> Str{ say "Hello, $name" } # Valid 
sub greeting2(Str $name--> Str{ say "Hello, $name" } # Valid 
sub favorite-number1(--> 42{        } # OUTPUT: 42 
sub favorite-number2(--> 42{ return } # 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 $word --> 123{ say $wordreturn}
my $value = foo("hello"); # OUTPUT: hello 
say $value;               # OUTPUT: 123 
# The code below will not compile 
sub foo(Str $word --> 123{ say $wordreturn $word}
my $value = foo("hello");
say $value;

The keyword returns following a signature declaration has the same function as --> with two caveats.

(1) This form is proposed for future removal. (2) This form does not work with constant values

    sub greeting(Str $namereturns Str { say "Hello, $name" } # Valid 
    sub favorite-number returns 42 {        } # This will fail. 

of is just the real name of the returns keyword.

    sub foo() of Int { 42 }# 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 { 1 };     # Valid 
    my 42 sub bad-answer {};  # This will fail.