Kotlin: unresolved reference to member variable?

Issue

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

Solution

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

Answered By – Tyler V

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published