Scala中辅助构造函数的问题

时间:2011-07-23 14:21:44

标签: scala constructor

我偶然发现了这个问题: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...
}

我对此解决方案的问题是主构造函数是公共的。因此,如果用户程序员创建了一个新帐户,他可以向其传递任意值。如果我总是希望它为零怎么办?无论如何,这是一个新账户,为什么它的金额不应该是零呢?

据我所知,用私有主构造函数创建公共类是不可能的。另一方面,辅助构造函数是可能的。 私有,这正是我试图做的。

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)
}

我确切地知道问题是什么,但我不知道如何修复它,这有点令人尴尬......

2 个答案:

答案 0 :(得分:10)

主要构造函数实际上可以是私有的:

case class Account private(balance:Int)

object Account {
  def apply() = new Account(0)
}

println(Account())
//doesn't compile: println(Account(100))

答案 1 :(得分:3)

Kim的优秀答案略有变化,没有伴侣对象:

class Account private(balance:Int) {
  def this() = {
    this(0)
  }  
  def deposit(amount: Int): Account = new Account(balance + amount)
}