Skip to content

Instantly share code, notes, and snippets.

@anant-sogani
Last active December 15, 2015 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anant-sogani/5276483 to your computer and use it in GitHub Desktop.
Save anant-sogani/5276483 to your computer and use it in GitHub Desktop.
p6 S02: Type Objects
Type Objects
[1] Every type has an undefined prototype object associated with it. It is responsible
for creating concrete objects of that type, among other things (see S12 for more on that).
[2] When a variable is declared to be of a particular type, it is actually being assigned
this prototype object (also called the type object for short).
my Int $x; # $x is assigned the type object "(Int)"
say $x; # (Int)
say $x.defined; # False
[3] To get a concrete object, a constructor method must be called.
my Int $x = $x.new; # $x is first assigned the type object, which is then used
# to create and assign a concrete Int object to $x.
say $x; # 0
say $x.defined; # True
TODO: Constructor with arguments.
[4] The type name used as a value is the type object itself.
Thus, the following statements are equivalent. All assign the type object to $x.
my Int $x;
my Int $x = Int;
my $x = Int;
And so are the following. All create a concrete Int object and assign to $x.
my Int $x = $x.new; # Shorthand: my Int $x .= new;
my Int $x = Int.new;
my $x = Int.new;
[5] The type object responds to a function call interface. Any argument passed to the
call is coerced to the type associated with the type object.
my $x = Int("5"); # String argument coerced into Int.
say $x; # 5
my $x = Int(5); # Number argument coerced into Int.
say $x; # 5
my $x = Int(); # Void argument coerced into Int.
say $x; # 0
Equivalent longer forms.
my Int $x = $x("5");
my Int $x = $x(5);
my Int $x = $x();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment