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

前端 未结 2 1885
我在风中等你
我在风中等你 2020-12-14 14:22

I want to access a member of the MainFragment class from PersonAdapter class but none of them are available. I tried making both the classes and the members public and priva

相关标签:
2条回答
  • 2020-12-14 15:07

    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

    0 讨论(0)
  • 2020-12-14 15:08

    In Kotlin, there are 2 types of the nested classes.

    1. Nested Class
    2. inner Class

    Nested class are not allowed to access the member of the outer class.

    If you want to access the member of outer class in the nested class then you need to define that nested class as inner class.

    class OuterClass{
    
        var name="john"
    
        inner class InnerClass{
    
           //....
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题