Created
April 21, 2026 19:35
-
-
Save gfldex/26e468a75581d3df948435c7eba8d50c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Pirate { | |
| has $.firstname; | |
| has $.lastname; | |
| has $.nickname is required; | |
| # multi method new(Str:D \s) { self.new: |(<firstname nickname lastname> Z=> s.split(/\h+/)) } | |
| multi method COERCE(Str:D \s) { | |
| self.new: |(<firstname nickname lastname> Z=> s.split(/\h+/)).Map | |
| } | |
| method Str(::?CLASS:D:) { | |
| $.firstname ~ ' ' ~ $.nickname ~ ' ' ~ $.lastname | |
| } | |
| } | |
| my @on-a-ship = ‘Jack "Seadog" Silver’, ‘Lara "Siren" Blackthorn’, ‘William "Quaffer" Darkwood’; | |
| for @on-a-ship -> Pirate() $p { | |
| dd $p; | |
| } | |
| # Coersion-types derive a new type-object form an existing type for the purpose of automatic coersion. Those can be used at any place where type-constrains are valid, including type-captures. To define a coersion-type provide the type name followed by a source type in parantheses. If the source type is `Any` it can be omitted. When assigning or binding a value to a symbol that is constraint by a coersion-type, the compiler will first look for a method of the same name in the source type and call this method. If no suche method is found in the source-type, the target-type is queried for a method called `COERCE` and if found, called with source-value. A new instance of the target-type must be returned by `COERCE`. If no `COERCE` is not found `new` will be called with the source-value as a positional argument. If this also fails the exception `X::Coerce::Impossible` is thrown. | |
| # | |
| # ### example ### | |
| # | |
| # It is possible to define `COERCE` as a submethod andoercion into `enum`s is handled by the compiler. | |
| # | |
| # The MOP shortcut `.^coarce` is supported. | |
| Pirate().^coerce(‘Jack "Seadog" Silver’); # equivalent to 'some string'.Pirate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment