我有一个包含几个包含整数的变量的类,我想要一个方法,根据调用将其中一个增加一定量。
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)
这可能甚至有用吗?或者我是否必须为每一个变量写一个“增加器”方法?
答案 0 :(得分: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
函数来处理执行操作以增加其中一个变量的业务逻辑。
答案 1 :(得分:1)
您无法在另一个方法中增加整数参数。如果要根据需要创建增强器方法,则必须将不可变对象传入方法。