I can’t reach any class member from a nested class in Kotlin

In Kotlin, nested classes cannot access the outer class instance by default, just like nested static classes can’t in Java.

To do that, add the inner modifier to the nested class:

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

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

Note that an inner class holds a reference to its containing class instance, which may affect the lifetime of the latter and potentially lead to a memory leak if the inner class instance is stored globally.

See: Nested classes in the language reference

Leave a Comment