I would like to be able to modify the properties i...
# codereview
e
I would like to be able to modify the properties in the initializer but nowhere else. Unfortunately, I don't think one can make private setters for properties declared as parameters. (Feel free to correct my terminology.)
Copy code
class 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?
Copy code
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)
    }
}
e
you don't need to give them different names,
Copy code
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)
    }
}
e
This is the second time you've been a big help to me in the past few days. Thanks so much, @ephemient!
k
There's a small caveat when you use the same names:
Copy code
class 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"
e
this.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't
e
I was going to use this as an example in a beginner class, but it might be more complicated than I thought.
If you don't use
var
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?
e
constructor params live through the whole constructor, so through all initializers and
init
blocks. nothing special happens when there's a property by the same name
just like how in a member function, parameters shadow properties by the same name too, but only within that function and the properties can be referenced with explicit
this.
qualification
e
I'm curious who you are in RL, @ephemient. You're clearly a Kotlin expert.
t
depending on what is your goal for this session of the beginners class, this difference between parameters and properties might get confusing and obfuscate the message. (2 cents not knowing what your goal, maybe showing this is exactly the point)