Scala中辅助构造函数的问题

agi*_*eel 1 constructor scala

我偶然发现了这个问题:在Scala中,我如何以无状态,功能性的方式建立银行账户?.建议的解决方案看似合理:

// Here is the important part of the answer
class Account(balance: Int) {
    def deposit(amount: Int): Account // the implementation was left out...
}
Run Code Online (Sandbox Code Playgroud)

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

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

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)
}
Run Code Online (Sandbox Code Playgroud)

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

Kim*_*bel 10

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

case class Account private(balance:Int)

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

println(Account())
//doesn't compile: println(Account(100))
Run Code Online (Sandbox Code Playgroud)