Basic multi dispatch
Multi dispatch allows to overload function names and let the types of its argument to determin which one is actually called.
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
Here, the two subs with the same name expect arguments of different types, Int
and Str
, respectively. Thus the call of twice
leads to execution of either twice(Int)
or twice(Str)
.
The keyword multi
is obligatory to tell the compiler that this sub may be overloaded. Would you omit multi
, you will get a compile error Redeclaration of routine twice
.