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

184
Views
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 answers
Answer question

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 Report

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 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!