Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading