我可以使用 MooseX::Declare 在类之外定义函数吗?

发布于 2024-07-12 13:35:20 字数 852 浏览 7 评论 0原文

我最近开始使用模块 MooseX::Declare。 我喜欢它的语法。 它优雅而整洁。 有没有人遇到过这样的情况:您想要在类中编写许多函数(其中一些很大)并且类定义运行到页面中? 是否有任何解决方法可以使类定义仅在类之外声明函数和真正的函数定义?

我正在寻找的是这样的东西 -

class BankAccount {
    has 'balance' => ( isa => 'Num', is => 'rw', default => 0 );
    # Functions Declaration.
    method deposit(Num $amount);
    method withdraw(Num $amount);
}

# Function Definition.
method BankAccount::deposit (Num $amount) {
    $self->balance( $self->balance + $amount );
}

method BankAccount::withdraw (Num $amount) {
    my $current_balance = $self->balance();
    ( $current_balance >= $amount )
    || confess "Account overdrawn";
    $self->balance( $current_balance - $amount );
}

我可以看到有一种方法可以使类可变。 有谁知道该怎么做?

I recently started using the module MooseX::Declare. I love it for its syntax. It's elegant and neat. Has anyone come across cases where you would want to write many functions (some of them big) inside a class and the class definition running into pages? Is there any workaround to make the class definition to just have the functions declared and the real function definition outside the class?

What I am look for is something like this -

class BankAccount {
    has 'balance' => ( isa => 'Num', is => 'rw', default => 0 );
    # Functions Declaration.
    method deposit(Num $amount);
    method withdraw(Num $amount);
}

# Function Definition.
method BankAccount::deposit (Num $amount) {
    $self->balance( $self->balance + $amount );
}

method BankAccount::withdraw (Num $amount) {
    my $current_balance = $self->balance();
    ( $current_balance >= $amount )
    || confess "Account overdrawn";
    $self->balance( $current_balance - $amount );
}

I can see that there is a way to make the class mutable. Does anyone know how to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

惟欲睡 2024-07-19 13:35:20

简单(但需要添加到文档中)。

class BankAccount is mutable {
}

顺便说一句,为什么要在类之外定义方法?

你可以走了

class BankAccount is mutable {
    method foo (Int $bar) {
         # do stuff
    }
}

Easy (but needs adding to the doc).

class BankAccount is mutable {
}

As an aside, why are you defining your methods outside the class?

You can just go

class BankAccount is mutable {
    method foo (Int $bar) {
         # do stuff
    }
}
冷弦 2024-07-19 13:35:20

我希望我的类定义简短,并给出该类用途的抽象概念。 我喜欢 C++ 中的实现方式,您可以选择使用范围解析运算符来定义内联函数或类外函数。 这使得类定义简短而整洁。 这就是我正在寻找的。

谢谢你的时间。

I want my class definition to be short, and to give an abstract idea of what the class is for. I like the way its been done in C++ where you have an option to define functions inline or outside the class using the scope resolution operator. This makes the class definition short and neat. This is what I am looking for.

Thanks for your time.

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