fun main(args: Array<String>) {
val wallet = Wallet(39.0, 14.5)
wallet++ //val cannot be resigned
}
data class Wallet(var dollarBalance:Double, var poundBalance:Double){
operator fun inc(): Wallet {
dollarBalance++
poundBalance++
return this
}
}
It seems that inc operator always resigns variable, even if it not required. In above example we only update object value, return the same object instance so val reassign is not required.
Yes, it does need to reassign the variable as it is just like a shortcut for that. And by the way Double is immutable so for different values it will always have different instances.
First of all we are talking about wallet instance witch is reassigned. inc method return the same instance, so reassign is redundant is this case - to fix it we need to change wallet to var, but the reassign really saves exactly the same instance (so what the point of saving it and making variable reference mutable).
The inc() and dec() functions must return a value, which will be assigned to the variable on which the ++ or – operation was used. They shouldn’t mutate the object on which the inc or dec was invoked.