On Thu May 10 06:12:35 2012, grond...@yahoo.fr wrote:
> I failed converting an object derived from Int using bless:
> 
> code:
> 
> class Foo is Int {};  sub somefoo returns Foo { Foo.bless: 13 }; say
> somefoo.WHAT;
> 
>     Error:
>     rakudo d61049: OUTPUT«Type check failed for return value␤  in sub
>     somefoo at /tmp/42g2EnvfAS:1␤ in block <anon> at
> /tmp/42g2EnvfAS:1␤␤»

Rakudo is actually correct here: in Perl 6, bless takes an already-built
object, and does initialization stuff (in particular it calls BUILDALL,
which in turns calls the BUILD submethods or does the default attribute
initialization). So Foo.bless: 13 actually returns the 13, and that
fails your type check.

So, how does one write the constructor for a class that inherits from a
value type?

A rakudo-specific answer is that you can write

class Foo is Int {
    method new($x) {
        nqp::box_i($x, self)
    }
}

The spec is silent on how to do it in a more general way.
A possible solution is to force all value types to provide a constructor
that you can inherit. So Int.new(4) would return a 4, but

class Foo is Int { }; Foo.new(4)

would return a 4 but of type Foo.

Cheers,
Moritz

Reply via email to