无法重新分配Android Val [英] Android val cannot be reassigned

查看:121
本文介绍了无法重新分配Android Val的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个名为notes的变量,当我尝试通过一种方法修改它时,android studio说

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

val无法重新分配

val cannot be reassigned

但是,如果我像这样访问变量,则可以修改它:this.notes.

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()
}

为什么会这样?

我来自JavaScript背景,请原谅我的无知.

I come from a Javascript background so excuse my ignorance.

推荐答案

您已命名两件事notes:

private var notes = emptyList<Note>()

和:

fun setNotes(notes: List<Note>)

因此,在setNotes()函数中,notes指的是函数参数.将其视为val,并且无法重新分配. this.notes指的是在NoteAdapter类上定义的notes属性.

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

这篇关于无法重新分配Android Val的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆