Does inc operator must always reassign variable?

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 {
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?

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

Basically you have implemented inc() incorrectly.

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.

1 Like

Embrace immutability

1 Like