在Scala中,我如何以无状态,功能性的方式建立银行账户?

时间:2011-07-23 04:15:53

标签: scala functional-programming

根据OO范例,您可能会有类似

的内容
class BankAccount(balance: Double) {
    def deposit(...)
    def withdraw(...)

}

我想知道你如何在功能范例中做同等的事情?

2 个答案:

答案 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

这样你就可以删除无效的交易(退款等)。