Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

526
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda