根据OO范例,您可能会有类似
的内容class BankAccount(balance: Double) {
def deposit(...)
def withdraw(...)
}
我想知道你如何在功能范例中做同等的事情?
答案 0 :(得分:12)
让BankAccount类中的每个方法都返回一个具有新余额的新BankAccount对象。这样,余额可以是不可变的变量。
class BankAccount(balance: Double) {
def deposit(amount: Double): BankAccount
def withdraw(amount: Double): BankAccount
}
答案 1 :(得分:1)
将帐户设为一系列交易,而不仅仅是当前金额:
case class Transaction(numberOfSeashells: Int)
case class Account(transactions: Iterable[Transaction])
def addNewTransaction(startingBalance: Int, t: Transaction) = startingBalance + t.numberOfSeashells
def balance(account: Account) = account.transactions.foldLeft(0)(addNewTransaction)
val acct = Account(List(Transaction(3), Transaction(-1)))
val newBalance = balance(acct)
结果:
scala> val acct = Account(List(Transaction(3), Transaction(-1)))
acct: Account = Account(List(Transaction(3), Transaction(-1)))
scala> val newBalance = balance(acct)
newBalance: Int = 2
这样你就可以删除无效的交易(退款等)。