Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android val cannot be reassigned

Tags:

android

kotlin

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.

like image 613
Diego Perdomo Avatar asked Sep 19 '25 04:09

Diego Perdomo


2 Answers

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>)
like image 114
CommonsWare Avatar answered Sep 20 '25 20:09

CommonsWare


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

like image 42
Ankit Tale Avatar answered Sep 20 '25 20:09

Ankit Tale