Let's say I have the following class:
class A {
has $.val;
method Str { $!val ~ 'µ' }
}
# Is this the right way of doing it?
multi infix:<~>(A:D $lhs, A:D $rhs) {
('(', $lhs.val, ',', $rhs.val, ')', 'µ').join;
}
How would I overload an operator (e.g., +
) for a class in the same manner as Str
in the previous class?
I guess this only works for methods that are invoked on an instance object and using the multi operator-type:<OP>(T $lhs, T $rhs) { }
syntax for operators is the right way to go about it but I'm unsure.
For instance, in Python there seems to be a correspondence between special methods named after the operators (e.g., operator.__add__
) and the operators (e.g., +
). Furthermore, any operator overloading for a custom class is done inside the class.
So yes, that is the correct way. If you want to override
+
, then the name of the sub to create isinfix:<+>
.You can also provide the case for type objects by using the
:U
"type smiley", e.g.:Hope this answers your question.
In Perl 6, operators are considered part of the current language. All things that relate to the current language are defined lexically (that is,
my
-scoped). Therefore, amulti
sub is the correct thing to use.If putting this code in a module, you would probably also want to mark the
multi
for the operator withis export
:So that it will be available to users who
use
orimport
the module (use
is in fact defined in terms ofimport
, andimport
imports symbols into the lexical scope).While there are some operators that by default delegate to methods (for example,
prefix:<+>
callsNumeric
), there's no 1:1 relation between the two, and for most operators their implementation is directly in the operatorsub
(or spread over manymulti sub
s).Further, the set of operators is open, so one is not restricted to overloading existing operators, but can also introduce new ones. This is encouraged when the new meaning for the operator is not clearly related to the normal semantics of the symbol used; for example, overloading
+
to do matrix addition would be sensible, but for something that couldn't possibly be considered a kind of addition, a new operator would be a better choice.