Thanks for the code. Fwiw I found it very readable.
Mu's BUILDALL returns the constructed object (per the self line at the end). I imagine a custom BUILDALL needs to do the same thing.
If you have the patience I'd appreciate you confirming that adding a trailing self line to Ack's BUILDALL fixes the problem you first posted about. (If so I'll update my original response to make it clear my guess about public attributes was a red herring.)
It's a mystery to me why converting a role to a class helped.
To wrap up I'll try to explain the error you just quoted. I'll go in to far more detail than I imagine you need in the hope it's helpful to someone some day.
I would appreciate confirmation that this error now makes sense to you as follows:
- Ack's BUILDALL returns Nil
A block of code in Perl 6 is interpreted as a semilist (semicolon separated list) of statements. When a block is evaluated it returns the value of its last statement unless the code explicitly specifies otherwise. In this case the last statement is a for loop:
unit class Game::Tetrachromat::Packet::Ack; # FTFY :)
...
method BUILDALL(|)
{
...
for ... {
...
}
}
A loop construct as the last statement is evaluated in sink context. Sink context means any value returned by an expression or statement gets thrown away -- down the sink as it were.
Perl 6 uses Nil to communicate nothingness. So Ack's BUILDALL attempts to return Nil.
Because Ack's BUILDALL's signature doesn't constrain what it returns, returning a Nil is fine and doesn't trigger a type error.
The code continues to run...
- The Nil becomes an Any
When a Scalar container is empty it pretends it contains a value, by default, an undefined Any. So if Nil gets assigned to any Scalar container with the default default the effect is indistinguishable from assigning it an undefined Any.
Somewhere between the return of Ack's BUILDALL and the completion of the PacketFactory read_buffer method code my $packet = $packet_class.new... the Nil becomes an Any. The my $packet declaration doesn't specify a type constraint. So the assignment of an Any (or a Nil which becomes an Any) proceeds without a type error.
The code continues to run...
- return $packet triggers a type error
Rakudo finally gets around to reporting a type error at line 79 of PacketFactory because the enclosing method, read_buffer, defines a return type in its signature: returns Game::Tetrachromat::Packet but $packet contains an Any.