gpt4 book ai didi

scala - 从辅助构造函数初始化 val

转载 作者:行者123 更新时间:2023-12-04 17:10:33 24 4
gpt4 key购买 nike

我有以下类代表一定数量的钱:

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)
}

关于scala - 从辅助构造函数初始化 val,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16760691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com