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

186
Visualizações
Android val cannot be reassigned

I defined a variable called notes, when i try to modify it from a method, android studio says

val cannot be reassigned

however i can modify it if i access the variable like this: this.notes.

class NoteAdapter(var context : Context) : RecyclerView.Adapter<NoteViewHolder>(){

private var notes = emptyList<Note>()

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder {
    var itemView = LayoutInflater.from(context).inflate(R.layout.note_item, parent, false)
    return NoteViewHolder(itemView)
}

override fun getItemCount(): Int {
    return notes.size
}

fun setNotes(notes: List<Note>) {
    this.notes = notes
    notifyDataSetChanged()
}

Why is this happening?

I come from a Javascript background so excuse my ignorance.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You named two things notes:

private var notes = emptyList<Note>()

and:

fun setNotes(notes: List<Note>)

So, in the setNotes() function, notes refers to the function parameter. That is treated as a val and cannot be reassigned. this.notes refers to the notes property defined on your NoteAdapter class.

In general, try to use different names, to reduce confusion. For example, you might use:

fun setNotes(replacementNotes: List<Note>)
over 4 years ago · Santiago Trujillo Relatório

0

In Kotlin,

val - When you declared any variable in Koltin as final variable so once assigned we cannot changes the value of it.

So use var when you need to define/change value while running application

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