Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!