0

我有一个包含多个变量的类,其中包含整数,我想要一种方法,根据调用将其中一个变量增加一定数量。

case class Bank {
  private var depo = 0
  private var loan = 0


  def deposit(amount: Int): Boolean = {
      if(amount>0) {
        depo += amount
        true
        } else false
  }

  def withdraw(amount: Int): Boolean = {
      if(amount > 0 && amount <= balance) {
        depo -= amount
        true
        } else false
  }

  def balance_=(b:Int) = {
    if(b >= 0) {
        if(b < depo) withdraw(depo-b) else deposit(b-depo)
    } else false
  }

  def balance = depo
}

当我想增加存款时,我只是打电话

myBank.balance += 10

但是当我现在想增加贷款时,我必须写一个额外的方法,对吧?是否有可能编写类似的方法

increaser(varToIncrease, amount)

这可能甚至有用吗?还是我必须为每个变量编写一个“increaser”方法?

4

2 回答 2

1

根据您的其他评论,看看这是否是您正在寻找的内容:

case class Bank {
  private var depo = 0
  private var loans = 0


  def deposit(amount: Int): Boolean = addTo(amount, depo += amount)

  def loan(amount: Int): Boolean = addTo(amount, loans += amount)

  private def addTo(amount:Int, func: => Unit):Boolean = {
    if(amount > 0) {
      func
      true
    } 
    else 
      false    
  }



  def withdraw(amount: Int): Boolean = {
      if(amount > 0 && amount <= balance) {
        depo -= amount
        true
        } else false
  }

  def balance_=(b:Int) = {
    if(b >= 0) {
        if(b < depo) withdraw(depo-b) else deposit(b-depo)
    } else false
  }

  def balance = depo
  def loanAmount = loans
}

object BankTest{
  def main(args: Array[String]) {
    val b = new Bank
    println("Starting amounts, " + b.balance + ", " + b.loanAmount)

    b.deposit(10)
    println(b.balance)
    b.deposit(-1)
    println(b.balance)

    b.loan(100)
    println(b.loanAmount)
    b.loan(-50)
    println(b.loanAmount)  
  }

}

我创建了两个公共函数来分别增加余额和贷款金额。然后,我创建了一个间隔addTo函数来处理执行操作以增加其中一个变量的业务逻辑。

于 2013-05-31T12:26:37.403 回答
1

您不能在另一个方法中增加整数参数。如果您想根据需要创建一个增量方法,则必须将一个不可变对象传递给该方法。

于 2013-05-31T16:14:05.613 回答