In Scala, how would I model a bank account in a stateless, functional manner?

↘锁芯ラ 提交于 2019-12-22 10:49:25

问题


Under an OO paradigm you could have something like

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

}

I'm wondering how you do the equivalent in the functional paradigm?


回答1:


Have each method in the BankAccount class return a new BankAccount object with the new balance. That way, the balance can be an immutable variable.

class BankAccount(balance: Double) {
    def deposit(amount: Double): BankAccount
    def withdraw(amount: Double): BankAccount
}



回答2:


Make the account be a series of transactions, not just a current amount:

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)

Result:

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

That way you can remove invalid transactions (chargebacks, etc).



来源:https://stackoverflow.com/questions/6798193/in-scala-how-would-i-model-a-bank-account-in-a-stateless-functional-manner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!