我试图从 type 强制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;
但是每当我尝试创建一个对象并将其传递给一个哈希数组时:
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 不应该能够处理包含在可能一起使用的模块中,以便可以单独使用这些模块吗?