In Kotlin, Why can the value of a val integer be reassigned by the inc() method?

184 views Asked by At

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

1

There are 1 answers

0
Sweeper On BEST ANSWER

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 a to a temporary storage a0.
  • Assign the result of a0.inc() to a.
  • Return a0 as the result of the expression.

Here you can see how inc's return value is used.