13

How to access the member of outer class from member function of inner class in kotlin. Consider the following code.

class A{
    var name: String

    class B{
        fun show(){
            print(name)          //<----- here ide shows error. name is not accessible
        }
    }
}

I am writing this code in android studio. It is working when written in java but not when we write code in kotlin.

Jaspal
  • 601
  • 2
  • 13
  • 23

2 Answers2

25

You should mark class B as inner:

class A{
  var name: String

  inner class B{
    fun show(){
      print(name)
    }
  }
}
Eric Martori
  • 2,885
  • 19
  • 26
2

Use like this

class A{
lateinit var name: String

inner class B{
    fun show(){
        print(name)
    }
}
}
sasikumar
  • 12,540
  • 3
  • 28
  • 48