在 Perl/Moose 中,我可以拥有两个具有相互依赖的默认值的属性吗?
我可以在穆斯做这个吗?
package SomeClass;
use Moose;
has start => (
isa => 'Int',
is => 'ro',
lazy => 1,
default => sub { $_[0]->end },
);
has end => (
isa => 'Int',
is => 'ro',
lazy => 1,
default => sub { $_[0]->start },
);
...
换句话说,我想要两个名为“start”和“end”的属性,如果只指定其中一个,我希望将另一个设置为相同的值。不指定其中任何一个都是错误的。
这种相互依赖的设置有效吗?
Can I do this in Moose?
package SomeClass;
use Moose;
has start => (
isa => 'Int',
is => 'ro',
lazy => 1,
default => sub { $_[0]->end },
);
has end => (
isa => 'Int',
is => 'ro',
lazy => 1,
default => sub { $_[0]->start },
);
...
In other words, I want two attributes called "start" and "end", and if only one of them is specified, I want the other one to be set to the same thing. Not specifying either one is an error.
Does this mutually-dependent setup work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,如果您通过验证至少指定了这些值之一来消除无限递归的可能性:
或者,您可以延迟对默认子项的检查:
Yes, if you remove the possibility of infinite recursion by verifying that at least one of these values is specified:
Alternatively, you could delay the check to the default subs:
就我个人而言,我会利用惰性来确保我不会陷入无限递归:
Personally, I'd take advantage of laziness to ensure that I didn't get caught in an infinite recursion: