我的以下课程代表一些钱:

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到辅助构造函数。有人可以帮忙吗?

最佳答案

反之亦然。

class Money private (pos: Boolean, initDollars: Int, initCents: Int) {

  require (initDollars >= 0 && initCents >= 0)

  def this(initDollars: Int, initCents: Int) = {
    this(true, initDollars, initCents)
  }

  val positive: Boolean = pos
  val dollars = initDollars + initCents/100
  val cents = initCents % 100
  private val totalAmount = dollars * 100 + cents

  def unary_- = new Money(!positive, dollars, cents)
}

08-04 13:25