Home > Net >  Kotlin: unresolved reference to member variable?
Kotlin: unresolved reference to member variable?

Time:06-08

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

CodePudding user response:

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
    }
}
  • Related