๐Ÿ“˜ Function overloading in Perl 6

๐Ÿ“˜ Function overloading in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


The multi keyword allows defining more than one function (or subroutine, or simply sub) with the same name. The only restriction is that those functions should have different signatures. In Perl 6, the signature of the sub is defined together with its name, and the arguments may be typed. In the case of multi subs, typed arguments make even more sense because they help to distinguish between different versions of the function with a single name and make a correct choice when the compiler needs to call one of them.

multi sub twice(Int $x) {
ย ย ย  return $x * 2;
}ย 

multi sub twice(Str $s) {
ย ย ย  return "$s, $s";
}ย 

say twice(42);ย  ย # 84
say twice("hi"); # hi, hi

As we have two functions here, one taking an integer argument and another expecting a string, the compiler can easily decide which one it should use.

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code