How to make a class completely immutable in Scala

I am trying to make the next class immutable. I know a theory about how to do this, but I believe that my implementation is wrong. You can help?

thank

Mutable class:

class BankAccount {
private var balance = 0
def deposit(amount: Int) {
    if (amount > 0)
    balance += amount
}
def withdraw(amount: Int): Int =
if (0 < amount && amount <= balance) {
    balance -= amount
    balance        
} else {
    error("insufficient funds")
}

Immutable class

case class BankAccount(b:Int) {

private def deposit(amount: Int):BankAccount {
    if (amount > 0)
    {
        return BankAccount(amount)
    }

}
private def withdraw(amount: Int): BankAccount ={
    if (0 < amount && amount <= balance) {
        return BankAccount(b-amount)       
    } else {
        error("insufficient funds")
    }
}  

}

+4
source share
2 answers

In functional programming, you do not change the state in place; instead, you create a new state and return it.

Here's how your use case can be solved with functional programming.

case class BankAccount(val money: Int)

The above case class represents BankAccount

Instead of mutating the state, create a new state with the calculated value and return it to the user.

def deposit(bankAccount: BankAccount, money: Int): BankAccount = {
  BankAccount(money + backAccount.money)
}

.

def withDraw(bankAccount: BankAccount, money: Int): BankAccount = {
  if (money >= 0 && bankAccount.money >= money) {
    BankAccount(bankAccount.money - money)
  } else error("in sufficient funds")
}

, .

, !!!

+7

-, : . : .

"" , final: .

, ? , deposit BankAccount, , . , , ! , .

: deposit BankAccount, BankAccount: amount , Unit. BankAccount Unit Any, Any. , . Option[BankAccount], a Try[BankAccount] Either[SomeErrorType, BankAccount], . . ( withdraw.)

- :

final case class BankAccount(balance: Int) {
  private def deposit(amount: Int) = copy(balance = balance + amount)
  private def withdraw(amount: Int) = copy(balance = balance - amount)       
}

. copy case, . , , .

, . ... ? , , , ! , ... ... ! 100 , 90 , 10 . 100 ! , , 110 90 ; 200 !

, .

-, , , " , , ", " , ", ( ) .

- , - . : - , - . , , , , . , :

final case class TransactionSlip(source: BankAccount, destination: BankAccount, amount: BigDecimal)

final case class BankAccount {
  def balance =
    TransactionLog.filter(slip.destination == this).map(_.amount).reduce(_ + _) - 
    TransactionLog.filter(slip.source == this).map(_.amount).reduce(_ + _)
}

, , , , , . , , . , , , , . , ( ).

, , , . , - , , , , .

+12

Source: https://habr.com/ru/post/1665355/


All Articles