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.
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>)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With