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
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 variablex
. Instead, it returns a value that is one more than the value ofx
. It does not changex
.As its documentation says:
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:Here you can see how
inc
's return value is used.