On 05/25/2014 09:50 AM, Kamil Kułaga wrote:
Hi,

My question is about passing parameters to .new method that do not
correspond to any field in class. This example;

use v6;

class PersonalId{
     has Int $.number;
     has Str $.full_name;
}

my Hash $p; #just because i'm scared of pair conversions
$p{"number"} = 13123123123;
$p{"full_name"} = "John Doe";
$p{"age"}=64;
$p{"shoesize"}=44;

say PersonalId.new(|%($p)).perl;
# PersonalId.new(number => 13123123123, full_name => "John Doe")

Works perfectly fine but I don't know whether I can rely on that. S12
speaks only about type objects: (It is allowed to pass type objects
that don't correspond to any parent class.)

Hello Kamil,
Why the behaviour above is correct and documented, you may find it bug-prone or inconvenient. To address that, I've ported MooseX::StrictConstructor to Perl 6[1]. Here's example usage demonstrated on a piece of code similar to yours:

use v6;
use ClassX::StrictConstructor;

class PersonalId does ClassX::StrictConstructor {
    has Int $.number;
    has Str $.full_name;
}

PersonalId.new(number => 7,
               full_name => "Edgar Poe",
               yada => 'yada');
# Output:
# The following attributes are not declared for type PersonalId: yada
#  in method new at /yada/yada/StrictConstructor.pm:32
#  in block  at test.pl:9

It may come to your liking :)

Best regards,
Tadeusz Sośnierz


[1] https://github.com/tadzik/ClassX-StrictConstructor

Reply via email to