I cannot contact a class member from a nested class in Kotlin

I want to access the MainFragment class from the PersonAdapter class, but none of them are available. I tried to make both classes and members public and private, but so far nothing has worked. I’m probably missing something obvious, but I just can’t understand.

class MainFragment : Fragment() {
    lateinit var personAdapter: PersonAdapter
    lateinit var personListener: OnPersonSelected
    private var realm: Realm by Delegates.notNull()
    lateinit var realmListener: RealmChangeListener<Realm>

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val v = inflater.inflate(R.layout.fragment_main, container, false)
        return v
    }

    class PersonAdapter() : RecyclerView.Adapter<ViewHolder>() {
        var localPersonList = personList

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.bindItems(localPersonList[position])

            holder.itemView.setOnClickListener {
                Toast.makeText(context, "click", Toast.LENGTH_SHORT).show()
                //I want to reach personListener from here
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
            val v = LayoutInflater.from(parent!!.context).inflate(R.layout.person_list_item, parent, false)
            return ViewHolder(v)
        }
    }}
+23
source share
2 answers

In Kotlin, nested classes cannot access an instance of an external class by default, like nested static classes in Java.

To do this, add the nested class modifier : inner

class MainFragment : Fragment() {
    // ...

    inner class PersonAdapter() : RecyclerView.Adapter<ViewHolder>() {
        // ...
    }
}

See: Nested classes in the language help

+56

Kotlin 2 .

.

, .

class OuterClass{

    var name="john"

    inner class InnerClass{

       //....
    }

}
+8

All Articles