【问题标题】:Problem with auxiliary constructors in ScalaScala中辅助构造函数的问题
【发布时间】: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)
}

我很清楚问题是什么,但我不知道如何解决它,这有点尴尬......

【问题讨论】:

标签: scala constructor


【解决方案1】:

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

case class Account private(balance:Int)

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

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

【讨论】:

    【解决方案2】:

    Kim 的优秀答案略有不同,没有伴生对象:

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

    【讨论】:

    • 谢谢,Kim 实际上已经修改了它。他的回答最初是这样的:“主构造函数可以是私有的”和一行代码,它显示了语法(这对我来说已经足够了)。但无论如何,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-08-20
    • 2015-01-28
    • 1970-01-01
    • 2012-05-12
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多