Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access variable from innerclass : Kotlin android

I am new to Kotlin development in android. here I am trying to access a variable defined in a class from it's inner class as below.

class MainActivity : AppCompatActivity() {      var frags: MutableList<Fragment> = mutableListOf()  //.............onCreate and other methods ....      internal class CustAdapter(var arrayList: ArrayList<NavigationData>) : RecyclerView.Adapter<CustAdapter.MyViewHolder>() {     override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {         holder!!.bindItems(arrayList[position])     }      override fun getItemCount(): Int {         return arrayList.size     }     override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustAdapter.MyViewHolder {         val v = LayoutInflater.from(parent.context).inflate(R.layout.navigation_item, parent, false)         return MyViewHolder(v)     }      class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {         fun bindItems(data: NavigationData) {               itemView.setOnClickListener {                    frags.add(BoardFrag()) ///// here i'm getting error "unresolved symbol"              }         }     } }     } 

inside inner class MyViewHolder it is not allowing me to access any variable of outer scope.

even I'm unable to access view ids imported from import kotlinx.android.synthetic.main.activity_main.* inside inner class methods.

I was able to access variables in such a way in java but i have read many question on stackoverflow but i didn't get answer yet.

like image 629
Irony Stack Avatar asked Sep 23 '17 04:09

Irony Stack


2 Answers

You should use the inner modifier in your adapter.

This modifier makes the inner class have access to the members of the outer class

Reference: https://kotlinlang.org/docs/reference/nested-classes.html

like image 131
Leandro Borges Ferreira Avatar answered Sep 18 '22 19:09

Leandro Borges Ferreira


Define your nested class as inner then you will be able to access an outer class member variable.

class OuterClass{  var accessMe ="access me from Inner Class"      inner class InnerClass{         //....           fun accessingOuterClassVariable(){             accessMe = "Now the variable is accessed"          }      }  } 
like image 40
Vivek Pratap Singh Avatar answered Sep 20 '22 19:09

Vivek Pratap Singh