Scala 中辅助构造函数的问题
我偶然发现了这个问题:在 Scala 中,我如何以无状态、功能性的方式对银行帐户进行建模?。所提出的解决方案看起来似乎合理:
// Here is the important part of the answer
class Account(balance: Int) {
def deposit(amount: Int): Account // the implementation was left out...
}
我对这个解决方案的问题是主构造函数是公共的。因此,如果用户程序员创建一个新帐户,他可以向其传递任意值。如果我总是希望它为零怎么办?无论如何,这是一个新帐户,为什么它的金额不是零?
据我所知,不可能使用私有主构造函数创建公共类。另一方面,辅助构造函数是可能的> 成为私密,这正是我试图做的。
class Account {
val balance = 0
private def this(amount: Int) = {
this()
balance = amount // won't compile since balance is a val
}
def deposit(amount: Int): Account = new Account(balance + amount)
}
我知道问题出在哪里,但不知道如何解决,这有点尴尬......
I stumbled over this question: In Scala, how would I model a bank account in a stateless, functional manner?. The proposed solution looks plausible:
// Here is the important part of the answer
class Account(balance: Int) {
def deposit(amount: Int): Account // the implementation was left out...
}
The problem I have with this solution is that the primary constructor is public. So if the user programmer creates a new account he can pass an arbitrary value to it. What if I always want it to be zero? It's a new account anyway, why should its amount be anything else than zero?
As far as I know it is impossible to make a public class with a private primary constructor. On the other hand it is possible for an auxiliary constructor to be private, which is exactly what I tried to do.
class Account {
val balance = 0
private def this(amount: Int) = {
this()
balance = amount // won't compile since balance is a val
}
def deposit(amount: Int): Account = new Account(balance + amount)
}
I know exactly what the problem is, but I have no idea how to fix it, which is kinda embarrassing...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
主构造函数实际上可以是私有的:
Primary constructors can in fact be private:
Kim 的出色答案略有不同,没有伴随对象:
A slight variation of Kim's excellent answer, without the companion object: