隐式创建鼠标类型约束

时间:2015-06-08 18:36:47

标签: perl perl-mouse

我正在尝试从类型ArrayRef[HashRef]强制转换为ArrayRef[MyModule::Object],但出于某种原因我收到了错误消息。下面是我的类型约束类:

package MyModule::Types;
use Mouse::Util::TypeConstraints;

subtype 'CoercedArrayRefOfMyModuleObjects' => as 'ArrayRef[MyModule::Object]';
coerce 'CoercedArrayRefOfMyModuleObjects'
    => from 'ArrayRef[HashRef]'
    => via { [map { MyModule::Object->new( %{$_} ) } @{$_}] };

no Mouse::Util::TypeConstraints;
1;

这是具有MyModule :: Objects的数组引用的类:

use strict;
package MyModule;
use Mouse;
use MyModule::Types;

has objects => ( 
    is => 'rw',
    isa => 'CoercedArrayRefOfMyModuleObjects',
    coerce => 1,
);

__PACKAGE__->meta->make_immutable();

1;

这是我的MyModule::Object课程:

use strict;
package MyModule::Object;
use Mouse;

has x => (
    is => 'rw',
    isa => 'Int',
);

__PACKAGE__->meta->make_immutable();

1;

但每当我尝试创建一个对象并传递一个哈希的arrayref:

my $obj = MyModule->new(objects => [{x => 1}, {x => 2}, {x => 3}]);

我收到以下错误:

The type constraint 'CoercedArrayRefOfMyModuleObjects' has already been created in Mouse::Util::TypeConstraints and cannot be created again in MyModule::Types ('CoercedArrayRefOfMyModuleObjects' is an implicitly created type constraint) at lib/MyModule/Types.pm line 41.

有谁知道这是为什么?

编辑:我认为这可能与我在多个地方use MyModule::Types有关。但我需要在多个位置使用它,以便模块可以单独使用。另外,由于某种原因,其他类型(我的TypeConstraints文件中定义了其他类型)似乎没有给我这个错误。不应该使用Mouse :: Util :: TypeConstraints来处理可能一起使用的模块,以便模块可以单独使用吗?

0 个答案:

没有答案