我有以下代表一些钱的类:
class Money(initDollars: Int, initCents: Int){
require (initDollars >= 0 && initCents >= 0)
private def this(positive: Boolean, initDollars: Int, initCents: Int) = {
this(initDollars, initCents)
//this.positive = positive
}
val positive: Boolean = true
val dollars = initDollars + initCents/100
val cents = initCents % 100
private val totalAmount = dollars * 100 + cents
def unary_- = new Money(!positive, dollars, cents)
}
object Money{
def apply(initDollars: Int, initCents: Int) = new Money(initDollars, initCents)
}
金额也可以是负数,我想像这样创建它:
val am = -Money(1, 20)
所以我想val positive
从一个辅助构造函数初始化,但我不能这样做,因为它是重新分配给 val。我也无法将val
参数列表添加到辅助构造函数。有人可以帮忙吗?