txt: ## objects.md
  ## Chunk 2 of 2
   self.bless(:$x, :$y);
        }
    }
  
    ```
  
    Do note, however, that `new` is a normal method and not involved in any of the construction process of `bless`. So any logic placed in the `new` method will not be called when using a different `new` method or a `new` of a subclass.
  
    Raku highlighting
  
    ```
    class Vector {
        has $.x;
        has $.y;
        has $.length;
        method new($x, $y) {
            self.bless(:$x, :$y, length => sqrt($x**2 * $y**2));
        }
    }
  
    class NamedVector is Vector {
        has $.name;
        method new($name, $x, $y) {
            self.bless(:$name, :$x, :$y);
        }
    }
  
    my $v = Vector.new: 3, 4;
    say $v.length; # OUTPUT: «5␤»
  
    my $f = NamedVector.new: 'Francis', 5, 12;
    say $f.length; # OUTPUT: «(Any)␤»
  
    ```
  
  Here is an example where we *enrich* the [`Str`](/type/Str) class with an auto-incrementing ID:
  
  ```raku
  class Str-with-ID is Str {
      my $counter = 0;
      has Int $.ID  is rw = 0;
  
      multi method new( $str ) {
          self.bless( value => $str );
      }
      submethod BUILD( :$!ID = $counter++ ) {}
  }
  
  say Str-with-ID.new("1.1,2e2").ID;                  # OUTPUT: «0␤»
  my $enriched-str = Str-with-ID.new("3,4");
  say "$enriched-str, {$enriched-str.^name}, {$enriched-str.ID}";
  # OUTPUT: «3,4, Str-with-ID, 1␤»
  
  ```
  
  We create a custom `new` since we want to be able to be able to initialize our new class with a bare string. `bless` will call `Str.BUILD` which will *capture* the value it's looking for, the pair `value => $str` and initialize itself. But we have to also initialize the properties of the subclass, which is why within `BUILD` we initialize `$.ID`. As seen in the output, the objects will be correctly initialized with an ID and can be used just like a normal [`Str`](/type/Str).
  
  ## [Object cloning](#Object_orientation "go to top of document")[§](#Object_cloning "direct link")
  
  The cloning is done using the [clone](/routine/clone) method available on all objects, which shallow-clones both public and private attributes. New values for *public* attributes can be supplied as named arguments.
  
  ```raku
  class Foo {
      has $.foo = 42;
      has $.bar = 100;
  }
  
  my $o1 = Foo.new;
  my $o2 = $o1.clone: :bar(5000);
  say $o1; # OUTPUT: «Foo.new(foo => 42, bar => 100)␤»
  say $o2; # OUTPUT: «Foo.new(foo => 42, bar => 5000)␤»
  
  ```
  
  See document for [clone](/routine/clone) for details on how non-scalar attributes get cloned, as well as examples of implementing your own custom clone methods.
  
  # [Roles](#Object_orientation "go to top of document")[§](#Roles "direct link")
  
  Roles are a collection of attributes and methods; however, unlike classes, roles are meant for describing only parts of an object's behavior; this is why, in general, roles are intended to be *mixed in* classes and objects. In general, classes are meant for managing objects and roles are meant for managing behavior and code reuse within objects.
  
  Roles use the keyword `role` preceding the name of the role that is declared. Roles are mixed in using the `does` keyword preceding the name of the role that is mixed in.
  
  Roles can also be mixed into a class using `is`. However, the semantics of `is` with a role are quite different from those offered by `does`. With `is`, a class is punned from the role, and then inherited from. Thus, there is no flattening composition, and none of the safeties which `does` provides.
  
  ```raku
  constant ⲧ = " " xx 4; #Just a ⲧab
  role Notable {
      has Str $.notes is rw;
  
      multi method notes() { "$!notes\n" };
      multi method notes( Str $note ) { $!notes ~= "$note\n" ~ ⲧ };
  
  }
  
  class Journey does Notable {
      has $.origin;
      has $.destination;
      has @.travelers;
  
      method Str { "⤷ $!origin\n" ~ ⲧ ~ self.notes() ~ "$!destination ⤶\n" };
  }
  
  my $trip = Journey.new( :origin<Here>, :destination<There>,
                          travelers => <þor Freya> );
  
  $trip.notes("First steps");
  notes $trip: "Almost there";
  print $trip;
  # OUTPUT:
  #⤷ Here
  #       First steps
  #       Almost there
  #
  #There ⤶
  
  ```
  
  Roles are immutable as soon as the compiler parses the closing curly brace of the role declaration.
  
  ## [Applying roles](#Object_orientation "go to top of document")[§](#Applying_roles "direct link")
  
  Role application differs significantly from class inheritance. When a role is applied to a class, the methods of that role are copied into the class. If multiple roles are applied to the same class, conflicts (e.g. attributes or non-multi methods of the same name) cause a compile-time error, which can be solved by providing a method of the same name in the class.
  
  This is much safer than multiple inheritance, where conflicts are never detected by the compiler, but are instead resolved to the superclass that appears earlier in the method resolution order, which might not be what the programmer wanted.
  
  For example, if you've discovered an efficient method to ride cows, and are trying to market it as a new form of popular transportation, you might have a class `Bull`, for all the bulls you keep around the house, and a class `Automobile`, for things that you can drive.
  
  ```raku
  class Bull {
      has Bool $.castrated = False;
      method steer {
          # Turn your bull into a steer
          $!castrated = True;
          return self;
      }
  }
  class Automobile {
      has $.direction;
      method steer($!direction) { }
  }
  class Taurus is Bull is Automobile { }
  
  my $t = Taurus.new;
  say $t.steer;
  # OUTPUT: «Taurus.new(castrated => Bool::True, direction => Any)␤»
  
  ```
  
  With this setup, your poor customers will find themselves unable to turn their Taurus and you won't be able to make more of your product! In this case, it may have been better to use roles:
  
  ```raku
  role Bull-Like {
      has Bool $.castrated = False;
      method steer {
          # Turn your bull into a steer
          $!castrated = True;
          return self;
      }
  }
  role Steerable {
      has Real $.direction;
      method steer(Real $d = 0) {
          $!direction += $d;
      }
  }
  class Taurus does Bull-Like does Steerable { }
  
  ```
  
  This code will die with something like:
  
  ｢text｣ without highlighting
  
  ```
  
  
  ```
  
  ===SORRY!===
  Method 'steer' must be resolved by class Taurus because it exists in
  multiple roles (Steerable, Bull-Like)
  
  
  ```
  
  
  ```
  
  This check will save you a lot of headaches:
  
  ```raku
  class Taurus does Bull-Like does Steerable {
      method steer($direction?) {
          self.Steerable::steer($direction)
      }
  }
  
  ```
  
  When a role is applied to a second role, the actual application is delayed until the second role is applied to a class, at which point both roles are applied to the class. Thus
  
  ```raku
  role R1 {
      # methods here
  }
  role R2 does R1 {
      # methods here
  }
  class C does R2 { }
  
  ```
  
  produces the same class `C` as
  
  ```raku
  role R1 {
      # methods here
  }
  role R2 {
      # methods here
  }
  class C does R1 does R2 { }
  
  ```
  
  ## [Stubs](#Object_orientation "go to top of document")[§](#Stubs "direct link")
  
  When a role contains a stubbed method, that is, a method whose code is limited to `...`, a non-stubbed version of a method of the same name must be supplied at the time the role is applied to a class. This allows you to create roles that act as abstract interfaces.
  
  ```raku
  role AbstractSerializable {
      method serialize() { ... }        # literal ... here marks the
                                        # method as a stub
  }
  
  # the following is a compile time error, for example
  #        Method 'serialize' must be implemented by Point because
  #        it's required by a role
  
  class APoint does AbstractSerializable {
      has $.x;
      has $.y;
  }
  
  # this works:
  class SPoint does AbstractSerializable {
      has $.x;
      has $.y;
      method serialize() { "p($.x, $.y)" }
  }
  
  ```
  
  The implementation of the stubbed method may also be provided by another role.
  
  ## [Inheritance](#Object_orientation "go to top of document")[§](#Inheritance_0 "direct link")
  
  Roles cannot inherit from classes, but they may *carry* classes, causing any class which does that role to inherit from the carried classes. So if you write:
  
  ```raku
  role A is Exception { }
  class X::Ouch does A { }
  X::Ouch.^parents.say # OUTPUT: «((Exception))␤»
  
  ```
  
  then `X::Ouch` will inherit directly from Exception, as we can see above by listing its parents.
  
  As they do not use what can properly be called inheritance, roles are not part of the class hierarchy. Roles are listed with the `.^roles` metamethod instead, which uses `transitive` as flag for including all levels or just the first one. Despite this, a class or instance may still be tested with smartmatches or type constraints to see if it does a role.
  
  ```raku
  role F { }
  class G does F { }
  G.^roles.say;                    # OUTPUT: «((F))␤»
  role Ur {}
  role Ar does Ur {}
  class Whim does Ar {}; Whim.^roles(:!transitive).say;   # OUTPUT: «((Ar))␤»
  say G ~~ F;                      # OUTPUT: «True␤»
  multi a (F $a) { "F".say }
  multi a ($a)   { "not F".say }
  a(G);                            # OUTPUT: «F␤»
  
  ```
  
  ## [Pecking order](#Object_orientation "go to top of document")[§](#Pecking_order "direct link")
  
  A method defined directly in a class will always override definitions from applied roles or from inherited classes. If no such definition exists, methods from roles override methods inherited from classes. This happens both when said class was brought in by a role, and also when said class was inherited directly.
  
  ```raku
  role M {
    method f { say "I am in role M" }
  }
  
  class A {
    method f { say "I am in class A" }
  }
  
  class B is A does M {
    method f { say "I am in class B" }
  }
  
  class C is A does M { }
  
  B.new.f; # OUTPUT: «I am in class B␤»
  C.new.f; # OUTPUT: «I am in role M␤»
  
  ```
  
  Note that each candidate for a multi-method is its own method. In this case, the above only applies if two such candidates have the same signature. Otherwise, there is no conflict, and the candidate is just added to the multi-method.
  
  ## [Automatic role punning](#Object_orientation "go to top of document")[§](#Automatic_role_punning "direct link")
  
  Any attempt to directly instantiate a role or use it as a type object will automatically create a class with the same name as the role, making it possible to transparently use a role as if it were a class.
  
  ```raku
  role Point {
      has $.x;
      has $.y;
      method abs { sqrt($.x * $.x + $.y * $.y) }
      method dimensions { 2 }
  }
  say Point.new(x => 6, y => 8).abs; # OUTPUT: «10␤»
  say Point.dimensions;              # OUTPUT: «2␤»
  
  ```
  
  We call this automatic creation of classes *punning*, and the generated class a *pun*.
  
  Punning is not caused by most [metaprogramming](/language/mop) constructs, however, as those are sometimes used to work directly with roles.
  
  ## [Parameterized roles](#Object_orientation "go to top of document")[§](#Parameterized_roles "direct link")
  
  Roles can be parameterized, by giving them a signature in square brackets:
  
  ```raku
  role BinaryTree[::Type] {
      has BinaryTree[Type] $.left;
      has BinaryTree[Type] $.right;
      has Type $.node;
  
      method visit-preorder(&cb) {
          cb $.node;
          for $.left, $.right -> $branch {
              $branch.visit-preorder(&cb) if defined $branch;
          }
      }
      method visit-postorder(&cb) {
          for $.left, $.right -> $branch {
              $branch.visit-postorder(&cb) if defined $branch;
          }
          cb $.node;
      }
      method new-from-list(::?CLASS:U: *@el) {
          my $middle-index = @el.elems div 2;
          my @left         = @el[0 .. $middle-index - 1];
          my $middle       = @el[$middle-index];
          my @right        = @el[$middle-index + 1 .. *];
          self.new(
              node    => $middle,
              left    => @left  ?? self.new-from-list(@left)  !! self,
              right   => @right ?? self.new-from-list(@right) !! self,
          );
      }
  }
  
  my $t = BinaryTree[Int].new-from-list(4, 5, 6);
  $t.visit-preorder(&say);    # OUTPUT: «5␤4␤6␤»
  $t.visit-postorder(&say);   # OUTPUT: «4␤6␤5␤»
  
  ```
  
  Here the signature consists only of a type capture, but any signature will do:
  
  ```raku
  enum Severity <debug info warn error critical>;
  
  role Logging[$filehandle = $*ERR] {
      method log(Severity $sev, $message) {
          $filehandle.print("[{uc $sev}] $message\n");
      }
  }
  
  Logging[$*OUT].log(debug, 'here we go'); # OUTPUT: «[DEBUG] here we go␤»
  
  ```
  
  You can have multiple roles of the same name, but with different signatures; the normal rules of multi dispatch apply for choosing multi candidates.
  
  ## [Mixins](#Object_orientation "go to top of document")[§](#Mixins_of_roles "direct link")
  
  Roles can be mixed into objects. A role's given attributes and methods will be added to the methods and attributes the object already has. Multiple mixins and anonymous roles are supported.
  
  ```raku
  role R { method Str() {'hidden!'} };
  my $i = 2 but R;
  sub f(\bound){ put bound };
  f($i); # OUTPUT: «hidden!␤»
  my @positional := <a b> but R;
  say @positional.^name; # OUTPUT: «List+{R}␤»
  
  ```
  
  Note that the object got the role mixed in, not the object's class or the container. Thus, @-sigiled containers will require binding to make the role stick as is shown in the example with `@positional`. Some operators will return a new value, which effectively strips the mixin from the result. That is why it might be more clear to mix in the role in the declaration of the variable using `does`:
  
  ```raku
  role R {};
  my @positional does R = <a b>;
  say @positional.^name; # OUTPUT: «Array+{R}␤»
  
  ```
  
  The operator `infix:<but>` is narrower than the list constructor. When providing a list of roles to mix in, always use parentheses.
  
  ```raku
  role R1 { method m {} }
  role R2 { method n {} }
  my $a = 1 but R1,R2; # R2 is in sink context, issues a WARNING
  say $a.^name;
  # OUTPUT: «Int+{R1}␤»
  my $all-roles = 1 but (R1,R2);
  say $all-roles.^name; # OUTPUT: «Int+{R1,R2}␤»
  
  ```
  
  If the role supplies exactly one attribute, an initializer can be passed in parentheses:
  
  ```raku
  role Named {
      has $.name;
  }
  my $hero = 1.Rat but Named('Remy');
  say $hero.name;     # OUTPUT: «Remy␤»
  
  ```
  
  Mixins can be used at any point in your object's life.
  
  ```raku
  # A counter for Table of Contents
  role TOC-Counter {
      has Int @!counters is default(0);
      method Str() { @!counters.join: '.' }
      method inc($level) {
          @!counters[$level - 1]++;
          @!counters.splice($level);
          self
      }
  }
  
  my Num $toc-counter = NaN;     # don't do math with Not A Number
  say $toc-counter;              # OUTPUT: «NaN␤»
  $toc-counter does TOC-Counter; # now we mix the role in
  $toc-counter.inc(1).inc(2).inc(2).inc(1).inc(2).inc(2).inc(3).inc(3);
  put $toc-counter / 1;          # OUTPUT: «NaN␤» (because that's numerical context)
  put $toc-counter;              # OUTPUT: «2.2.2␤» (put will call TOC-Counter::Str)
  
  ```
  
  Roles can be anonymous.
  
  ```raku
  my %seen of Int is default(0 but role :: { method Str() {'NULL'} });
  say %seen<not-there>;          # OUTPUT: «NULL␤»
  say %seen<not-there>.defined;  # OUTPUT: «True␤» (0 may be False but is well defined)
  say Int.new(%seen<not-there>); # OUTPUT: «0␤»
  
  ```
  
  # [Metaobject programming and introspection](#Object_orientation "go to top of document")[§](#Metaobject_programming_and_introspection "direct link")
  
  Raku has a metaobject system, which means that the behavior of objects, classes, roles, grammars, enums, etc. are themselves controlled by other objects; those objects are called *metaobjects*. Metaobjects are, like ordinary objects, instances of classes, in this case we call them *metaclasses*.
  
  For each object or class you can get the metaobject by calling `.HOW` on it. Note that although this looks like a method call, it works more like a macro.
  
  So, what can you do with the metaobject? For one you can check if two objects have the same metaclass by comparing them for equality:
  
  ```raku
  say 1.HOW ===   2.HOW;      # OUTPUT: «True␤»
  say 1.HOW === Int.HOW;      # OUTPUT: «True␤»
  say 1.HOW === Num.HOW;      # OUTPUT: «False␤»
  
  ```
  
  Raku uses the word *HOW* (Higher Order Workings) to refer to the metaobject system. Thus it should be no surprise that in Rakudo, the class name of the metaclass that controls class behavior is called `Perl6::Metamodel::ClassHOW`. For each class there is one instance of `Perl6::Metamodel::ClassHOW`.
  
  But the metamodel does much more for you. For example, it allows you to introspect objects and classes. The calling convention for methods on metaobjects is to call the method on the metaobject and pass in the object of interest as first argument to the object. So to get the name of the class of an object, you could write:
  
  ```raku
  my $object = 1;
  my $metaobject = 1.HOW;
  say $metaobject.name($object);      # OUTPUT: «Int␤»
  
  # or shorter:
  say 1.HOW.name(1);                  # OUTPUT: «Int␤»
  
  ```
  
  (The motivation is that Raku also wants to allow a more prototype-based object system, where it's not necessary to create a new metaobject for every type).
  
  There's a shortcut to keep from using the same object twice:
  
  ```raku
  say 1.^name;                        # OUTPUT: «Int␤»
  # same as
  say 1.HOW.name(1);                  # OUTPUT: «Int␤»
  
  ```
  
  See [`Metamodel::ClassHOW`](/type/Metamodel/ClassHOW) for documentation on the metaclass of `class` and also the [general documentation on the metaobject protocol](/language/mop).
  