Aaron Sherman writes:
> The question I have is: how do classes control their conversion? In C++
> you can overload the casting operator for any time and/or define a
> constructor for the receiving type.
>
> I can imagine how you would define the constructor on the receiving type
> in Perl 6, but there's no "casting" syntax in Perl 6. Should we pretend
> there is for purposes of defining a conversion and allow:
>
> class foo {
> ...
> sub prefix:IO::Socket(foo $f) returns(IO::Socket) {...}
> }
>
> or did Larry mention a way to define a converter and I missed it?
Yep, that's what happened. See Apocalypse 12 under "Overloading."
Specifically, it's defined by the operator coerce:as. So:
class Foo {...}
multi sub *coerce:as (Foo $foo, ::Bar $class) {
say "Converting to $class.name()"
}
my Bar $bar = Foo.new; # Converting to Bar
You can do it explicitly, too:
my $bar = Foo.new as Bar;
Luke