在斯卡拉,我将如何建立一个无状态,功能性的银行账户? [英] In Scala, how would I model a bank account in a stateless, functional manner?

查看:142
本文介绍了在斯卡拉,我将如何建立一个无状态,功能性的银行账户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个面向对象的范例中,你可能有类似于

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

}

我想知道你是如何在功能范式中做等价的吗?

解决方案

让BankAccount类中的每个方法用新的余额返回一个新的BankAccount对象。这样,余额可以是一个不可变的变量。

  class BankAccount(balance:Double){
def deposit(金额:双倍):BankAccount
def withdraw(金额:双倍):BankAccount
}


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?

解决方案

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
}

这篇关于在斯卡拉,我将如何建立一个无状态,功能性的银行账户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆