我有一个类包含多个变量包含整数,我想要一个方法增加其中一个取决于一定数量的调用。如何增加多个变量?
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)
的方法的可能性是可能的,甚至有用吗?或者我必须为每个变量写一个“增量”方法吗?
为什么不简单'+ ='? –
我同意@ om-nom-nom。为什么有一个函数来执行添加,除非在这个函数中发生了额外的事情(如副作用,这应该可以避免) – cmbaxter
感谢您的答案。我对Scala很陌生。我的问题是,当我想将var x增加100时,我用x.increase(100)来做这件事,但是当我想增加var y时,我必须为y写第二种方法。这对我来说没有意义,但我不知道如何解决这个问题。 – Mikkel