为什么我可以将类名用作 Moose 类型,但不能将其作为类型联合的一部分?
我可以这样做:
package Foo;
use Moose;
has 'time' => (
is => 'rw',
isa => 'DateTime'
);
package main;
use DateTime;
my $a = Foo->new(time => DateTime->now);
但不能这样做:
package Foo;
use Moose;
has 'time' => (
is => 'rw',
isa => 'DateTime | Str'
);
package main;
use DateTime;
my $a = Foo->new(time => DateTime->now);
因为它引发了异常:
Could not locate type constraint (DateTime) for the union
at /opt/xt/xt-perl/lib/site_perl/5.8.8/Moose/Util/TypeConstraints.pm line 89
没有首先定义子类型。为什么会这样,有没有办法解决它(除了定义检查“isa”的子类型之外)?
I can do this:
package Foo;
use Moose;
has 'time' => (
is => 'rw',
isa => 'DateTime'
);
package main;
use DateTime;
my $a = Foo->new(time => DateTime->now);
But not this:
package Foo;
use Moose;
has 'time' => (
is => 'rw',
isa => 'DateTime | Str'
);
package main;
use DateTime;
my $a = Foo->new(time => DateTime->now);
As it raises an exception:
Could not locate type constraint (DateTime) for the union
at /opt/xt/xt-perl/lib/site_perl/5.8.8/Moose/Util/TypeConstraints.pm line 89
Without defining a SubType first. Why is this, and is there a way around it (apart from defining a subtype that checks 'isa')?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当 Moose 创建类型联合时,它必须知道联合的所有组件。在这种情况下,它还不知道 DateTime 类型。然而,当您在 Moose 中创建属性并且 Moose 无法识别该类型时,它会假设您需要
isa
中字符串的类类型,并且会这样做。您只需加载 Moose::Util::TypeConstraints 并执行即可解决问题When Moose creates a type union it has to know all the components of the union. In this case, it does not yet know the DateTime type. However when you create an attribute in Moose and Moose does not recognize the type, it makes an assumption that you want a class-type of the string in
isa
and just does that. You can solve you issue by simply loading Moose::Util::TypeConstraints and doing