File tree Expand file tree Collapse file tree 1 file changed +24
-2
lines changed Expand file tree Collapse file tree 1 file changed +24
-2
lines changed Original file line number Diff line number Diff line change @@ -558,8 +558,30 @@ C<Cool> is the type that the routine accepts as input.
558
558
If the accepted input type is L < Any|/type/Any > , you can abbreviate C < Int(Any) >
559
559
to C < Int() > .
560
560
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.
563
585
564
586
= end pod
565
587
You can’t perform that action at this time.
0 commit comments