为什么我可以将类名用作 Moose 类型,但不能将其作为类型联合的一部分?

发布于 2024-10-20 20:40:37 字数 671 浏览 2 评论 0原文

我可以这样做:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

◇流星雨 2024-10-27 20:40:37

当 Moose 创建类型联合时,它必须知道联合的所有组件。在这种情况下,它还不知道 DateTime 类型。然而,当您在 Moose 中创建属性并且 Moose 无法识别该类型时,它会假设您需要 isa 中字符串的类类型,并且会这样做。您只需加载 Moose::Util::TypeConstraints 并执行即可解决问题

class_type 'DateTime';

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

class_type 'DateTime';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文