Raku Books / Perl 6 at a Glance / Code Organization / Function overloading
Sub overloading with subtypes
Multi subs can be made even more specific by using subtypes. In Perl
6, subtypes are created with the subset keyword. A subtype
definition takes one of the existing types and adds a restriction to
select the values to be included in the subtype range.
The following lines give a clear view of how subtypes are defined.
From the same integer type, Int, the Odd
subtype selects only the odd numbers, while the Even
subtype picks only the even numbers.
subset Odd of Int where {$^n % 2 == 1};
subset Even of Int where {$^n % 2 == 0};CodeBlockPlaceholder2raku-static multi sub testnum(Odd $x) { say “$x is odd”; }
multi sub testnum(Even $x) { say “$x is even”; } CodeBlockPlaceholder3raku-static testnum($x); } CodeBlockPlaceholder4 1 is odd 2 is even 3 is odd 4 is even ```
Course navigation
← Function overloading | Modules →