Unable to access variable from innerclass : Kotlin android

后端 未结 3 646
离开以前
离开以前 2021-01-03 18:06

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 : Ap         


        
相关标签:
3条回答
  • 2021-01-03 18:46

    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"
    
            }
    
        }
    
    }
    
    0 讨论(0)
  • 2021-01-03 18:50

    to answer this question for the fast an easy way i would do something like following :

    class OuterClass{
    
    private var accessibleInside: CustomObject? = null
    inner class InnerClass{
    
        //....
    }
    

    now the CustomObject could be anything from Context to String hope this helps someone.

    0 讨论(0)
  • 2021-01-03 19:05

    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

    0 讨论(0)
提交回复
热议问题