简体   繁体   中英

Kotlin: unresolved reference to member variable?

My class NotesListAdapter has a member variable context but when I try to call this member variable in the below function, I get an unresolved reference error. I'm new to Kotlin, so I'm confused about what is going on here.

class NotesListAdapter(context:Context,list:List<Notes>,listener:NotesClickListener) : RecyclerView.Adapter<NotesViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotesViewHolder {
        return NotesViewHolder(LayoutInflater.from(context).inflate(R.layout.notes_list,parent,false))
    }
}

When you pass the variable in as (context: Context you have created a local variable that is only available during initialization, not a class member. For example, in this case s is not available to use in printmys() but it is available in init or in inline declarations:

class TestClass(s: String) {

    fun printmys() {
        println(s) // not valid
    }

    init {
        println(s) // valid
    }

    private val mys = s // also valid
}

To declare it as a private class member so you can use it in your functions, add a declaration like private val or var before it like this:

class NotesListAdapter(private val context: Context

Or, using the example above

class TestClass(private val s: String) {
    fun printmys() {
        println(s) // valid
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM