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…
Primary constructors can in fact be private: