Ellen Spertus
09/18/2022, 1:25 AMclass USMoney(var dollars: Int, var cents: Int) {
init {
require(dollars >= 0 && cents >= 0)
if (cents >= NUM_CENTS_PER_DOLLAR) {
dollars += cents / NUM_CENTS_PER_DOLLAR
cents %= NUM_CENTS_PER_DOLLAR
}
}
}
I rewrote the code as shown. Is this a good approach and, if so, is there a standard naming convention for the parameters/properties?
class USMoney(_dollars: Int, _cents: Int) {
val dollars = _dollars + _cents / NUM_CENTS_PER_DOLLAR
val cents = _cents % NUM_CENTS_PER_DOLLAR
init {
require(_dollars >= 0 && _cents >= 0)
}
}
ephemient
09/18/2022, 1:30 AMclass USMoney(dollars: Int, cents: Int) {
val dollars = dollars + cents / NUM_CENTS_PER_DOLLAR
val cents = cents % NUM_CENTS_PER_DOLLAR
init {
require(dollars >= 0 && cents >= 0)
}
}
Ellen Spertus
09/18/2022, 1:32 AMKlitos Kyriacou
09/18/2022, 11:28 AMclass USMoney(dollars: Int, cents: Int) {
val dollars = dollars + cents / NUM_CENTS_PER_DOLLAR
val cents = cents % NUM_CENTS_PER_DOLLAR
val repr = "$%d.$02d".format(dollars, cents)
The values used in repr
are the original given arguments and not the "cleaned up" values, so you'd end up with "$1.103" instead of "$2.03"ephemient
09/18/2022, 8:09 PMthis.dollars
always refers to the property. if you are in a position where the constructor params are visible then the simple name refers to them, otherwise it doesn'tEllen Spertus
09/18/2022, 9:32 PMEllen Spertus
09/18/2022, 9:38 PMvar
or val
before a formal parameter in the primary constructor, does that mean it is just an ordinary (but long-lived) parameter, rather than a property?ephemient
09/18/2022, 10:03 PMinit
blocks. nothing special happens when there's a property by the same nameephemient
09/18/2022, 10:04 PMthis.
qualificationEllen Spertus
09/18/2022, 10:32 PMthanksforallthefish
09/19/2022, 5:51 AM