Consider the following,
val x: Int = 0
val variables cannot be changed so doing x += 1 wouldn't work
The compiler says Val cannot be reassigned
why then does x.inc() work fine
doesn't x.inc() reassign the value from 0 to 1
x.inc() does not increment the variable x. Instead, it returns a value that is one more than the value of x. It does not change x.
val x = 0
x.inc() // 1 is retuned, but discarded here
print(x) // still 0!
As its documentation says:
Returns this value incremented by one.
That might seem like a very useless method. Well, this is what Kotlin uses to implement operator overloading for the postfix/prefix ++ operator.
When you do a++, for example, the following happens:
- Store the initial value of
ato a temporary storagea0.- Assign the result of
a0.inc()toa.- Return
a0as the result of the expression.
Here you can see how inc's return value is used.