Skip to content

Commit c874e11

Browse files
committed
Merge pull request #109 from LLFourn/master
added example of type coercions for non builtin types
2 parents ccf8229 + 7485ab2 commit c874e11

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

lib/Language/functions.pod

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -558,8 +558,30 @@ C<Cool> is the type that the routine accepts as input.
558558
If the accepted input type is L<Any|/type/Any>, you can abbreviate C<Int(Any)>
559559
to C<Int()>.
560560
561-
Coercion types are supposed to work wherever types work, but Rakudo currently
562-
(2015.02) only implements them for subroutine parameters.
561+
The coercion works simply by looking for a method with the same name
562+
as the target type. So you can define coercions for your own types like so:
563+
564+
class MyModule::Foo {
565+
has $.msg = "I'm a foo!";
566+
567+
method MyModule::Bar {
568+
::('MyModule::Bar').new(:msg($.msg ~ ' But I am now Bar.'));
569+
}
570+
}
571+
572+
class MyModule::Bar {
573+
has $.msg;
574+
}
575+
576+
sub print-bar(MyModule::Bar() $bar) {
577+
say $bar.WHAT; #MyModule::Bar
578+
say $bar.msg; #I'm a foo! But I am now Bar.
579+
}
580+
581+
print-bar MyModule::Foo.new;
582+
583+
Coercion types are supposed to work wherever types work, but Rakudo
584+
currently (2015.02) only implements them for subroutine parameters.
563585
564586
=end pod
565587

0 commit comments

Comments
 (0)