In Object orientation§
See primary documentation in context for self.
Inside a method, the term self is available and bound to the invocant object. self can be used to call further methods on the invocant, including constructors:
class Box { has $.data; method make-new-box-from() { self.new: data => $!data; } }
self can be used in class or instance methods as well, though beware of trying to invoke one type of method from the other:
class C { method g() { 42 } method f(::?CLASS:U:) { self.g } method d(::?CLASS:D:) { self.f } } C.f; # OUTPUT: «42» C.new.d; # This will fail. CATCH { default { put .^name ~ ":\n" ~ .Str } }; # OUTPUT: «X::Parameter::InvalidConcreteness: # Invocant of method 'f' must be a type object of type 'C', # not an object instance of type 'C'. Did you forget a 'multi'?»
self can also be used with attributes, as long as they have an accessor. self.a will call the accessor for an attribute declared as has $.a. However, there is a difference between self.a and $.a, since the latter will itemize; $.a will be equivalent to self.a.item or $(self.a).
class A { has Int @.numbers; has $.x = (1, 2, 3); method show-diff() { .say for self.x; .say for $.x } method twice { self.times: 2 } method thrice { $.times: 3 } method times($val = 1) { @!numbers.map(* * $val).list } }; my $obj = A.new(numbers => [1, 2, 3]); $obj.show-diff; # OUTPUT: «123(1 2 3)» say $obj.twice; # OUTPUT: «(2 4 6)» say $obj.thrice; # OUTPUT: «(3 6 9)»
The colon-syntax for method arguments is supported for method calls using either self or the shortcut, as illustrated with the methods twice and thrice in the example above.
Note that if the relevant methods bless, CREATE of Mu are not overloaded, self will point to the type object in those methods.
On the other hand, the submethods BUILD and TWEAK are called on instances, in different stages of initialization. Submethods of the same name from subclasses have not yet run, so you should not rely on potentially virtual method calls inside these methods.