简体   繁体   English

如何从Kotlin的内部类访问外部类的成员?

[英]how to access member of outer class from inner class in Kotlin?

How to access the member of outer class from member function of inner class in kotlin. 如何在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. 我在android studio中编写此代码。 It is working when written in java but not when we write code in kotlin. 使用Java编写时可以正常工作,但是使用Kotlin编写代码时则无法工作。

You should mark class B as inner : 您应该将class B标记为inner

class A{
  var name: String

  inner class B{
    fun show(){
      print(name)
    }
  }
}

Use like this 这样使用

class A{
lateinit var name: String

inner class B{
    fun show(){
        print(name)
    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM