【发布时间】:2011-07-23 14:21:43
【问题描述】:
我偶然发现了这个问题:In Scala, how would I model a bank account in a stateless, functional manner?。提议的解决方案看起来是合理的:
// Here is the important part of the answer
class Account(balance: Int) {
def deposit(amount: Int): Account // the implementation was left out...
}
这个解决方案的问题是主构造函数是公共的。因此,如果用户程序员创建了一个新帐户,他可以将任意值传递给它。如果我总是希望它为零怎么办?反正是新账户,为什么金额不为零?
据我所知,用私有主构造函数创建一个公共类是不可能的。另一方面,辅助构造函数是可能的 成为 private,这正是我试图做的。
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)
}
我很清楚问题是什么,但我不知道如何解决它,这有点尴尬......
【问题讨论】:
-
@oluies -- 这不是一个骗子。这是一个不同的问题,有相同的答案。
标签: scala constructor