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.
Since inner classes are members of the outer class, you can apply any access modifiers like private , protected to your inner class which is not possible in normal classes. Since the nested class is a member of its enclosing outer class, you can use the dot ( . ) notation to access the nested class and its members.
Of your inner class is non static then create an object of innerClass. OuterClass out = new OuterClass(); OuterClass. InnerClass inn = out.
Kotlin nested class is by default static, hence, it can be accessed without creating any object of that class but with the help of . dot operator. Same time we cannot access members of the outer class inside a nested class.
You can access the static variable of an outer class just using the class name.
You should mark class B
as 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)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With