Does inc operator must always reassign variable?


#1
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.

is it a bug or language design?


#2

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.


#3

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


#4

The problem is that inc() is expected to return a value to be set to the var, it doesn’t know if it is the same instance or not.


#5

Basically you have implemented inc() incorrectly.

https://kotlinlang.org/docs/reference/operator-overloading.html

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.

Your inc implementation mutates the object.


#6

Embrace immutability