Skip to content

Commit

Permalink
Merge pull request #109 from LLFourn/master
Browse files Browse the repository at this point in the history
added example of type coercions for non builtin types
  • Loading branch information
LLFourn committed Jul 27, 2015
2 parents ccf8229 + 7485ab2 commit c874e11
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions lib/Language/functions.pod
Expand Up @@ -558,8 +558,30 @@ C<Cool> is the type that the routine accepts as input.
If the accepted input type is L<Any|/type/Any>, you can abbreviate C<Int(Any)>
to C<Int()>.
Coercion types are supposed to work wherever types work, but Rakudo currently
(2015.02) only implements them for subroutine parameters.
The coercion works simply by looking for a method with the same name
as the target type. So you can define coercions for your own types like so:
class MyModule::Foo {
has $.msg = "I'm a foo!";
method MyModule::Bar {
::('MyModule::Bar').new(:msg($.msg ~ ' But I am now Bar.'));
}
}
class MyModule::Bar {
has $.msg;
}
sub print-bar(MyModule::Bar() $bar) {
say $bar.WHAT; #MyModule::Bar
say $bar.msg; #I'm a foo! But I am now Bar.
}
print-bar MyModule::Foo.new;
Coercion types are supposed to work wherever types work, but Rakudo
currently (2015.02) only implements them for subroutine parameters.
=end pod

Expand Down

0 comments on commit c874e11

Please sign in to comment.