Scala 中辅助构造函数的问题

发布于 2024-11-25 12:34:24 字数 894 浏览 1 评论 0原文

我偶然发现了这个问题:在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

假装爱人 2024-12-02 12:34:24

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

case class Account private(balance:Int)

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

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

Primary constructors can in fact be private:

case class Account private(balance:Int)

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

println(Account())
//doesn't compile: println(Account(100))
夜空下最亮的亮点 2024-12-02 12:34:24

Kim 的出色答案略有不同,没有伴随对象:

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

A slight variation of Kim's excellent answer, without the companion object:

class Account private(balance:Int) {
  def this() = {
    this(0)
  }  
  def deposit(amount: Int): Account = new Account(balance + amount)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文