txt: ## objects.md
  ## Chunk 1 of 2
  Object orientation
  
  Object orientation in Raku
  
  Raku provides strong support for [Object Oriented Programming (OOP)](https://en.wikipedia.org/wiki/Object-oriented_programming). Although Raku allows programmers to program in multiple paradigms, Object Oriented Programming is at the heart of the language.
  
  Raku comes with a wealth of predefined types, which can be classified in two categories: regular and [*native* types](/language/nativetypes). Everything that you can store in a variable is either a *native value* or an *object*. That includes literals, types (type objects), code and containers.
  
  Native types are used for low-level types (like `uint64`). Even if *native* types do not have the same capabilities as objects, if you call methods on them, they are automatically *boxed* into normal objects.
  
  Everything that is not a *native* value is an *object*. Objects do allow for both [inheritance](https://en.wikipedia.org/wiki/Object-oriented_programming#Inheritance_and_behavioral_subtyping) and [encapsulation](https://en.wikipedia.org/wiki/Object-oriented_programming#Encapsulation).
  
  # [Using objects](#Object_orientation "go to top of document")[§](#Using_objects "direct link")
  
  To call a method on an object, add a dot, followed by the method name:
  
  ```raku
  say "abc".uc;
  # OUTPUT: «ABC␤»
  
  ```
  
  This calls the `uc` method on `"abc"`, which is an object of type [`Str`](/type/Str). To supply arguments to the method, add arguments inside parentheses after the method.
  
  ```raku
  my $formatted-text = "Fourscore and seven years ago...".indent(8);
  say $formatted-text;
  # OUTPUT: «        Fourscore and seven years ago...␤»
  
  ```
  
  `$formatted-text` now contains the above text, but indented 8 spaces.
  
  Multiple arguments are separated by commas:
  
  ```raku
  my @words = "Abe", "Lincoln";
  @words.push("said", $formatted-text.comb(/\w+/));
  say @words;
  # OUTPUT: «[Abe Lincoln said (Fourscore and seven years ago)]␤»
  
  ```
  
  Similarly, multiple arguments can be specified by placing a colon after the method and separating the argument list with a comma:
  
  ```raku
  say @words.join('--').subst: 'years', 'DAYS';
  # OUTPUT: «Abe--Lincoln--said--Fourscore and seven DAYS ago␤»
  
  ```
  
  Since you have to put a `:` after the method if you want to pass arguments without parentheses, a method call without a colon or parentheses is unambiguously a method call without an argument list:
  
  ```raku
  say 4.log:   ; # OUTPUT: «1.38629436111989␤» ( natural logarithm of 4 )
  say 4.log: +2; # OUTPUT: «2␤» ( base-2 logarithm of 4 )
  say 4.log  +2; # OUTPUT: «3.38629436111989␤» ( natural logarithm of 4, plus 2 )
  ```
  
  Many operations that don't look like method calls (for example, smartmatching or interpolating an object into a string) might result in method calls under the hood.
  
  Methods can return mutable containers, in which case you can assign to the return value of a method call. This is how read-writable attributes to objects are used:
  
  ```raku
  $*IN.nl-in = "\r\n";
  
  ```
  
  Here, we call method `nl-in` on the `$*IN` object, without arguments, and assign to the container it returned with the [`=`](/routine/= (item assignment)) operator.
  
  All objects support methods from class [`Mu`](/type/Mu), which is the type hierarchy root. All objects derive from [`Mu`](/type/Mu).
  
  Object equality needs a specific operator: [`eqv`](/language/operators#infix_eqv), the structural comparison operator:
  
  ```raku
  class Foo {
      has $.bar;
      has $.baz
  };
  my $bar = "42";
  my $baz = 24;
  my $zipi = Foo.new( :$baz, :$bar);
  my $zape = Foo.new( :$bar, :$baz);
  say $zipi eqv $zape; # OUTPUT: «True␤»
  
  ```
  
  Object identity, on the other hand, uses `===`. Using it above will return `False`, for instance.
  
  ## [Type objects](#Object_orientation "go to top of document")[§](#Type_objects "direct link")
  
  Types themselves are objects and you can get the *type object* by writing its name:
  
  ```raku
  my $int-type-obj = Int;
  
  ```
  
  You can request the type object of anything by calling the `WHAT` method, which is actually a macro in method form:
  
  ```raku
  my $int-type-obj = 1.WHAT;
  
  ```
  
  Type objects (other than [`Mu`](/type/Mu)) can be compared for equality with the [`===`](/routine/===) identity operator:
  
  ```raku
  sub f(Int $x) {
      if $x.WHAT === Int {
          say 'you passed an Int';
      }
      else {
          say 'you passed a subtype of Int';
      }
  }
  
  ```
  
  Although, in most cases, the [`.isa`](/routine/isa) method will suffice:
  
  ```raku
  sub f($x) {
      if $x.isa(Int) {
          ...
      }
      ...
  }
  
  ```
  
  Subtype checking is done by [smartmatching](/language/operators#infix_~~):
  
  ```raku
  if $type ~~ Real {
      say '$type contains Real or a subtype thereof';
  }
  
  ```
  
  # [Classes](#Object_orientation "go to top of document")[§](#Classes "direct link")
  
  Classes are declared using the `class` keyword, typically followed by a name.
  
  ```raku
  class Journey { }
  
  ```
  
  This declaration results in a type object being created and installed in the current package and current lexical scope under the name `Journey`. You can also declare classes lexically:
  
  ```raku
  my class Journey { }
  
  ```
  
  This restricts their visibility to the current lexical scope, which can be useful if the class is an implementation detail nested inside a module or another class.
  
  ## [Attributes](#Object_orientation "go to top of document")[§](#Attributes "direct link")
  
  Attributes are variables that exist per instance of a class; when instantiated to a value, the association between the variable and its value is called a property. They are where the state of an object is stored. In Raku, all attributes are *private*, which means they can be accessed directly only by the class instance itself. They are typically declared using the `has` declarator and the `!` twigil.
  
  ```raku
  class Journey {
      has $!origin;
      has $!destination;
      has @!travelers;
      has $!notes;
  }
  
  ```
  
  Alternatively, you can omit the twigil, which will still create the private attribute (with a `!` twigil), and will also create an alias that binds the name (without the twigil) to that attribute. Thus, you can declare the same class above with
  
  ```raku
  class Journey {
      has $origin;
      has $destination;
      has @travelers;
      has $notes;
  }
  
  ```
  
  If you declare the class like this, you can subsequently access the attributes either with or without the twigil – e.g., `$!origin` and `$origin` refer to same attribute.
  
  While there is no such thing as a public (or even protected) attribute, there is a way to have accessor methods generated automatically: replace the `!` twigil with the `.` twigil (the `.` should remind you of a method call).
  
  ```raku
  class Journey {
      has $.origin;
      has $.destination;
      has @!travelers;
      has $.notes;
  }
  
  ```
  
  This defaults to providing a read-only accessor. In order to allow changes to the attribute, add the [is rw](/routine/is%20rw) trait:
  
  ```raku
  class Journey {
      has $.origin;
      has $.destination;
      has @!travelers;
      has $.notes is rw;
  }
  
  ```
  
  Now, after a `Journey` object is created, its `.origin`, `.destination`, and `.notes` will all be accessible from outside the class, but only `.notes` can be modified.
  
  If an object is instantiated without certain attributes, such as origin or destination, we may not get the desired result. To prevent this, provide default values or make sure that an attribute is set on object creation by marking an attribute with an [is required](/routine/is%20required) trait.
  
  ```raku
  class Journey {
      # error if origin is not provided
      has $.origin is required;
      # set the destination to Orlando as default (unless that is the origin!)
      has $.destination = self.origin eq 'Orlando' ?? 'Kampala' !! 'Orlando';
      has @!travelers;
      has $.notes is rw;
  }
  
  ```
  
  Since classes inherit a default constructor from [`Mu`](/type/Mu) and we have requested that some accessor methods are generated for us, our class is already somewhat functional.
  
  ```raku
  # Create a new instance of the class.
  my $vacation = Journey.new(
      origin      => 'Sweden',
      destination => 'Switzerland',
      notes       => 'Pack hiking gear!'
  );
  
  # Use an accessor; this outputs Sweden.
  say $vacation.origin;
  
  # Use a rw accessor to change the value.
  $vacation.notes = 'Pack hiking gear and sunglasses!';
  
  ```
  
  Note that, although the default constructor can initialize read-only attributes, it will only set attributes that have an accessor method. That is, even if you pass `travelers => ["Alex", "Betty"]` to the default constructor, the attribute `@!travelers` is not initialized.
  
  ## [Methods](#Object_orientation "go to top of document")[§](#Methods "direct link")
  
  Methods are declared with the `method` keyword inside a class body.
  
  ```raku
  class Journey {
      has $.origin;
      has $.destination;
      has @!travelers;
      has $.notes is rw;
  
      method add-traveler($name) {
          if $name ne any(@!travelers) {
              push @!travelers, $name;
          }
          else {
              warn "$name is already going on the journey!";
          }
      }
  
      method describe() {
          "From $!origin to $!destination"
      }
  }
  
  ```
  
  A method can have a signature, just like a subroutine. Attributes can be used in methods and can always be used with the `!` twigil, even if they are declared with the `.` twigil. This is because the `.` twigil declares an attribute and generates an accessor method for it.
  
  Looking at the code above, there is a subtle but important difference between using `$!origin` and `$.origin` in the method `describe`. `$!origin` is an inexpensive and obvious lookup of the attribute. `$.origin` is a method call and thus may be overridden in a subclass. Only use `$.origin` if you want to allow overriding.
  
  Unlike subroutines, additional named arguments will not produce compile time or runtime errors. That allows chaining of methods via [Re-dispatching](/language/functions#Re-dispatching).
  
  You may write your own accessors to override any or all of the autogenerated ones.
  
  ```raku
  my $ⲧ = " " xx 4; # A tab-like thing
  class Journey {
      has $.origin;
      has $.destination;
      has @.travelers;
      has Str $.notes is rw;
  
      multi method notes() { "$!notes\n" };
      multi method notes( Str $note ) { $!notes ~= "$note\n$ⲧ" };
  
      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 ⤶
  
  ```
  
  The declared multi method `notes` overrides the auto-generated methods implicit in the declaration of `$.notes`, using a different signature for reading and writing.
  
  Please note that in `notes $trip: "Almost there"` we are using indirect invocant syntax, which puts first the method name, then the object, and then, separated by a colon, the arguments: `method invocant: arguments`. We can use this syntax whenever it feels more natural than the classical period-and-parentheses one. It works exactly in the same way.
  
  Note how the call to the `notes` method in the [`Str`](/routine/Str) method is made on `self`. Writing method calls this way will leave the return value of the method as is with regards to containers. To containerize return values, you can make method calls on a sigil instead of `self`. This calls various methods on the return value of the method depending on the sigil used to containerize it:
  
  | Sigil | Method |
  | --- | --- |
  | $ | item |
  | @ | list |
  | % | hash |
  | & | item |
  
  For example, the [`Str`](/routine/Str) method of `Journey` can be rewritten not to use the `~` operator by embedding a sigiled method call in the string it returns:
  
  ```raku
  method Str { "⤷ $!origin\n$ⲧ$.notes()$!destination ⤶\n" }
  
  ```
  
  The syntax used to update `$.notes` changed in this section with respect to the previous [Attributes](#Attributes) section. Instead of an assignment:
  
  ```raku
  $vacation.notes = 'Pack hiking gear and sunglasses!';
  
  ```
  
  we now do a method call:
  
  ```raku
  $trip.notes("First steps");
  
  ```
  
  Classes Overriding the default auto-generated accessor means it is no longer available to provide a mutable container on return for an assignment. A method call is the preferred approach to adding computation and logic to the update of an attribute (see 'programmatic use' of such calls in the following section). Many modern languages can update an attribute by overloading assignment with a “setter” method. While Raku can overload the assignment operator for this purpose with a [`Proxy`](/type/Proxy) object, overloading assignment to set attributes with complex logic is currently discouraged as [weaker object oriented design](https://6guts.wordpress.com/2016/11/25/perl-6-is-biased-towards-mutators-being-really-simple-thats-a-good-thing/).
  
  ## [Class and instance methods](#Object_orientation "go to top of document")[§](#Class_and_instance_methods "direct link")
  
  Method names can be resolved at runtime with the `.""` operator which enables programmatic use of such names. For example, since an attribute name is also a method, we can show attribute `a`'s value by calling the `a` method:
  
  ```raku
  class A { has $.a = 9 }
  my $method = 'a';
  A.new."$method"().say;
  # OUTPUT: «9␤»
  
  ```
  
  A method with arguments may be called in a similar manner:
  
  ```raku
  class B {
      has $.b = 9;
      method mul($n) {
          $!b * $n
      }
  }
  my $method = 'mul';
  B.new."$method"(6).say;
  # OUTPUT: «54␤»
  
  ```
  
  A method's signature can have an *explicit invocant* as its first parameter followed by a colon, which allows for the method to refer to the object it was called on.
  
  ```raku
  class Foo {
      method greet($me: $person) {
          say "Hi, I am $me.^name(), nice to meet you, $person";
      }
  }
  Foo.new.greet("Bob");    # OUTPUT: «Hi, I am Foo, nice to meet you, Bob␤»
  
  ```
  
  Providing an invocant in the method signature also allows for defining the method as either as a class method, or as an object method, through the use of [type constraints](/language/signatures#Type_constraints). The `::?CLASS` variable can be used to provide the class name at compile time, combined with either `:U` (for class methods AKA static in other languages) or `:D` (for instance methods).
  
  ```raku
  class Pizza {
      has $!radius = 42;
      has @.ingredients;
  
      # class method: construct from a list of ingredients
      method from-ingredients(::?CLASS:U $pizza: @ingredients) {
          $pizza.new( ingredients => @ingredients );
      }
  
      # instance method
      method get-radius(::?CLASS:D:) { $!radius }
  }
  my $p = Pizza.from-ingredients: <cheese pepperoni vegetables>;
  say $p.ingredients;     # OUTPUT: «[cheese pepperoni vegetables]␤»
  say $p.get-radius;      # OUTPUT: «42␤»
  say Pizza.get-radius;   # This will fail.
  CATCH { default { put .^name ~ ":\n" ~ .Str } };
  # OUTPUT: «X::Parameter::InvalidConcreteness:␤
  #          Invocant of method 'get-radius' must be
  #          an object instance of type 'Pizza',
  #          not a type object of type 'Pizza'.
  #          Did you forget a '.new'?»
  
  ```
  
  A method can be both a class and object method by using the [multi](/syntax/multi) declarator:
  
  ```raku
  class C {
      multi method f(::?CLASS:U:) { say "class method"  }
      multi method f(::?CLASS:D:) { say "object method" }
  }
  C.f;       # OUTPUT: «class method␤»
  C.new.f;   # OUTPUT: «object method␤»
  
  ```
  
  ## [`self`](#Object_orientation "go to top of document")[§](#self "direct link")
  
  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:
  
  ```raku
  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:
  
  ```raku
  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)`.
  
  ```raku
  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: «1␤2␤3␤(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`](/type/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.
  
  ## [Private methods](#Object_orientation "go to top of document")[§](#Private_methods "direct link")
  
  Methods with an exclamation mark `!` before the method name are not callable from anywhere outside the defining class; such methods are private in the sense that they are not visible from outside the class that declares them. Private methods are invoked with an exclamation mark instead of a dot:
  
  ```raku
  class FunMath {
      has $.value is required;
      method !do-subtraction( $num ) {
          if $num ~~ Str {
              return $!value + (-1 * $num.chars);
          }
          return $!value + (-1 * $num);
      }
      method minus( $minuend: $subtrahend ) {
          # invoking the private method on the explicit invocant
          $minuend!do-subtraction($subtrahend);
      }
  }
  my $five = FunMath.new(value => 5);
  say $five.minus(6);         # OUTPUT: «-1␤»
  
  say $five.do-subtraction(6);
  CATCH { default { put .^name ~ ":\n" ~ .Str } }
  # OUTPUT: «X::Method::NotFound:
  # No such method 'do-subtraction' for invocant of type
  # 'FunMath'. Did you mean '!do-subtraction'?␤»
  
  ```
  
  Private methods have their own namespace. They're not virtual, i.e., private methods cannot be overridden within the inheriting class to provide any polymorphic behavior, thus missing ones are detected at compile time. Unlike in some languages where `private` is an [accessibility modifier](https://en.wikipedia.org/wiki/Access_modifiers) on a method, in Raku "private methods" and "methods" are quite different things - that is to say, it's better to read "private method" as a compound noun rather than an adjective describing a noun.
  
  Private methods are not inherited by subclasses.
  
  ## [Submethods](#Object_orientation "go to top of document")[§](#Submethods "direct link")
  
  Submethods are public methods that will not be inherited by subclasses. The name stems from the fact that they are semantically similar to subroutines.
  
  Submethods are useful for object construction and destruction tasks, as well as for tasks that are so specific to a certain type that subtypes would certainly have to override them.
  
  For example, the [default method new](/type/Mu#method_new) calls submethod `BUILD` on each class in an [inheritance](#Inheritance) chain:
  
  ```raku
  class Point2D {
      has $.x;
      has $.y;
  
      submethod BUILD(:$!x, :$!y) {
          say "Initializing Point2D";
      }
  }
  
  class InvertiblePoint2D is Point2D {
      submethod BUILD() {
          say "Initializing InvertiblePoint2D";
      }
      method invert {
          self.new(x => - $.x, y => - $.y);
      }
  }
  
  say InvertiblePoint2D.new(x => 1, y => 2);
  # OUTPUT: «Initializing Point2D␤»
  # OUTPUT: «Initializing InvertiblePoint2D␤»
  # OUTPUT: «InvertiblePoint2D.new(x => 1, y => 2)␤»
  
  ```
  
  See also: [Object construction](#Object_construction).
  
  ## [Inheritance](#Object_orientation "go to top of document")[§](#Inheritance "direct link")
  
  Classes can have *parent classes*.
  
  ```raku
  class Child is Parent1 is Parent2 { }
  
  ```
  
  If a method is called on the child class, and the child class does not provide that method, the method of that name in one of the parent classes is invoked instead, if it exists. The order in which parent classes are consulted is called the *method resolution order* (MRO). Raku uses the [C3 method resolution order](https://en.wikipedia.org/wiki/C3_linearization). You can ask a type for its MRO through a call to its metaclass:
  
  ```raku
  say List.^mro;      # OUTPUT: «((List) (Cool) (Any) (Mu))␤»
  
  ```
  
  If a class does not specify a parent class, [`Any`](/type/Any) is assumed by default. All classes directly or indirectly derive from [`Mu`](/type/Mu), the root of the type hierarchy.
  
  All calls to public methods are "virtual" in the C++ sense, which means that the actual type of an object determines which method to call, not the declared type:
  
  ```raku
  class Parent {
      method frob {
          say "the parent class frobs"
      }
  }
  
  class Child is Parent {
      method frob {
          say "the child's somewhat more fancy frob is called"
      }
  }
  
  my Parent $test;
  $test = Child.new;
  $test.frob;          # calls the frob method of Child rather than Parent
  # OUTPUT: «the child's somewhat more fancy frob is called␤»
  
  ```
  
  If you want to explicitly call the parent method on a child object, refer to its full name in the parent namespace:
  
  ```raku
  $test.Parent::frob;  # calls the frob method of Parent
  # OUTPUT: «the parent class frobs␤»
  
  ```
  
  ## [Delegation](#Object_orientation "go to top of document")[§](#Delegation "direct link")
  
  Delegation is a technique whereby an object, the *delegator*, accepts a method call but has designated another object, the *delegatee*, to process the call in its place. In other words, the *delegator* publishes one or more of the *delegatee*'s methods as its own.
  
  In Raku, delegation is specified by applying the [handles](/language/typesystem#trait_handles) trait to an attribute. The arguments provided to the trait specify the methods the object and the *delegatee* attribute will have in common. Instead of a list of method names, you can provide a [`Pair`](/type/Pair) (to rename; the key becomes the new name), a [`Regex`](/type/Regex) (to handle every method with a matching name), a [`Whatever`](/type/Whatever) (to delegate all methods that the attribute [can](/type/Metamodel/ClassHOW#method_can) call), or a [`HyperWhatever`](/type/HyperWhatever) (to delegate all method calls, even ones that will lead to the attribute's [FALLBACK](/routine/FALLBACK) method). You can also provide a [`List`](/type/List) providing any of those items to delegate multiple methods. Note that the [`Regex`](/type/Regex), [`Whatever`](/type/Whatever), and [`HyperWhatever`](/type/HyperWhatever) forms do not delegate any methods that the class has inherited (for example, from [`Any`](/type/Any) or [`Mu`](/type/Mu)) but that explicitly naming the method does delegate it.
  
  ```raku
  class Book {
      has Str  $.title;
      has Str  $.author;
      has Str  $.language;
      has Cool $.publication;
  }
  
  class Product {
      has Book $.book handles('title', 'author', 'language', year => 'publication');
  }
  
  my $book = Book.new:
      :title<Dune>,
      :author('Frank Herbert'),
      :language<English>,
      :publication<1965>
  ;
  
  given Product.new(:$book) {
      say .title;    # OUTPUT: «Dune␤»
      say .author;   # OUTPUT: «Frank Herbert␤»
      say .language; # OUTPUT: «English␤»
      say .year;     # OUTPUT: «1965␤»
  }
  
  ```
  
  In the example above, the class `Product` defines the attribute `$.book` and mark it with the `handles` trait to specify the methods that will be forwarded to the class `Book` whenever they're invoked on an instance object of the `Product` class. There are a few things to notice here:
  
  * We didn't write any methods inside the `Product` class that we invoked in its instance object. Instead, we instructed the class to delegate a call to any those methods to the `Book` class.
  * We've specified the method names `title`, `author`, and `language` as they appear in the `Book` class. On the other hand, we've renamed the `publication` method to `year` by providing the appropriate [`Pair`](/type/Pair).
  
  Delegation can be used as an alternative to inheritance by delegating to the parent class and not inheriting all of its methods. For example, the following `Queue` class delegates several methods proper of queues to the [`Array`](/type/Array) class while also providing a preferred interface for a few of those methods (e.g., `enqueue` for `push`):
  
  ```raku
  class Queue {
      has @!q handles(
          enqueue => 'push', dequeue => 'shift',
          'push', 'shift', 'head', 'tail', 'elems', 'splice'
      );
  
      method gist {
          '[' ~ @!q.join(', ') ~ ']'
      }
  }
  
  my Queue $q .= new;
  $q.enqueue($_) for 1..5;
  $q.push(6);
  say $q.shift;                  # OUTPUT: «1␤»
  say $q.dequeue while $q.elems; # OUTPUT: «2␤3␤4␤5␤6␤»
  
  $q.enqueue($_) for <Perl Python Raku Ruby>;
  say $q.head;                   # OUTPUT: «Perl␤»
  say $q.tail;                   # OUTPUT: «Ruby␤»
  say $q;                        # OUTPUT: «[Perl, Python, Raku, Ruby]␤»
  $q.dequeue while $q.elems;
  say $q;                        # OUTPUT: «[]␤»
  
  ```
  
  ## [Object construction](#Object_orientation "go to top of document")[§](#Object_construction "direct link")
  
  Objects are generally created through method calls, either on the type object or on another object of the same type.
  
  Class [`Mu`](/type/Mu) provides a constructor method called [new](/routine/new), which takes named [arguments](/language/functions#Arguments) and uses them to initialize public attributes.
  
  ```raku
  class Point {
      has $.x;
      has $.y;
  }
  my $p = Point.new( x => 5, y => 2);
  #             ^^^ inherited from class Mu
  say "x: ", $p.x;
  say "y: ", $p.y;
  # OUTPUT: «x: 5␤»
  # OUTPUT: «y: 2␤»
  
  ```
  
  `Mu.new` calls method [bless](/routine/bless) on its invocant, passing all the named [arguments](/language/functions#Arguments). `bless` creates the new object, and then walks all subclasses in reverse method resolution order (i.e. from [`Mu`](/type/Mu) to most derived classes). In each class `bless` executes the following steps in the order given here:
  
  * It checks for the existence of a method named `BUILD`. If the method exists, the method is called with all the named arguments it received (from the `new` method).
  * If no `BUILD` method was found, the public attributes from this class are initialized from named arguments of the same name.
  * All attributes that have not been touched in any of the previous steps have their default values applied:
  
    `has $.attribute = 'default value';`
  * `TWEAK` is called should it exist. It will receive the same arguments `BUILD` receives.
  
  This object construction scheme has several implications:
  
  * Named arguments to the default `new` constructor (inherited from [`Mu`](/type/Mu)) can correspond directly to public attributes of any of the classes in the method resolution order, or to any named parameter of any `BUILD` or `TWEAK` submethod.
  * Custom `BUILD` methods should always be submethods, otherwise they are inherited to subclasses and prevent default attribute initialization (item two in the above list) should the subclass not have its own `BUILD` method.
  * `BUILD` may set an attribute, but it does not have access to the contents of the attribute declared as its default as they are only applied later. `TWEAK` on the other hand is called after default values have been applied and will thus find the attributes initialized. So it can be used to check things or modify attributes after object construction:
  
    Raku highlighting
  
    ```
    class RectangleWithCachedArea {
        has ($.x1, $.x2, $.y1, $.y2);
        has $.area;
        submethod TWEAK() {
            $!area = abs( ($!x2 - $!x1) * ( $!y2 - $!y1) );
        }
    }
  
    say RectangleWithCachedArea.new( x2 => 5, x1 => 1, y2 => 1, y1 => 0).area;
    # OUTPUT: «4␤»
  
    ```
  * Since passing arguments to a routine binds the arguments to the parameters, one can simplify BUILD methods by using the attribute as a parameter.
  
    A class using ordinary binding in the `BUILD` method:
  
    Raku highlighting
  
    ```
    class Point {
        has $.x;
        has $.y;
  
        submethod BUILD(:$x, :$y) {
            $!x := $x;
            $!y := $y;
        }
    }
    my $p1 = Point.new( x => 10, y => 5 );
  
    ```
  
    The following `BUILD` method is equivalent to the above:
  
    Raku highlighting
  
    ```
    submethod BUILD(:$!x, :$!y) {
        # Nothing to do here anymore, the signature binding
        # does all the work for us.
    }
  
    ```
  * In order to use default values together with a `BUILD()` method one can't use parameter binding of attributes, as that will always touch the attribute and thus prevent the automatic assignment of default values (step three in the above list). Instead one would need to conditionally assign the value:
  
    Raku highlighting
  
    ```
    class A {
        has $.attr = 'default';
        submethod BUILD(:$attr) {
            $!attr = $attr if defined $attr;
        }
    }
    say A.new(attr => 'passed').raku;
    say A.new().raku;
    # OUTPUT: «A.new(attr => "passed")␤»
    # OUTPUT: «A.new(attr => "default")␤»
  
    ```
  
    It's simpler to set a default value of the `BUILD` parameter instead though:
  
    Raku highlighting
  
    ```
    class A {
        has $.attr;
        submethod BUILD(:$!attr = 'default') {}
    }
  
    ```
  * Be careful when using parameter binding of attributes when the attribute has a special type requirement such as an [`Int`](/type/Int) type. If `new` is called without this parameter, then a default of [`Any`](/type/Any) will be assigned, which will cause a type error. The easy fix is to add a default value to the `BUILD` parameter.
  
    Raku highlighting
  
    ```
    class A {
        has Int $.attr;
        submethod BUILD(:$!attr = 0) {}
    }
    say A.new(attr => 1).raku;
    say A.new().raku;
    # OUTPUT: «A.new(attr => 1)␤»
    # OUTPUT: «A.new(attr => 0)␤»
  
    ```
  * `BUILD` allows to create aliases for attribute initialization:
  
    Raku highlighting
  
    ```
    class EncodedBuffer {
        has $.enc;
        has $.data;
  
        submethod BUILD(:encoding(:$!enc), :$!data) { }
    }
    my $b1 = EncodedBuffer.new( encoding => 'UTF-8', data => [64, 65] );
    my $b2 = EncodedBuffer.new( enc      => 'UTF-8', data => [64, 65] );
    #  both enc and encoding are allowed now
  
    ```
  * Note that the name `new` is not special in Raku. It is merely a common convention, one that is followed quite thoroughly in [most Raku classes](/routine/new). You can call `bless` from any method, or use `CREATE` to fiddle around with low-level workings.
  * If you want a constructor that accepts positional arguments, you must write your own `new` method:
  
    Raku highlighting
  
    ```
    class Point {
        has $.x;
        has $.y;
        method new($x, $y) {
           