Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 656
Jaspal Avatar asked Apr 12 '19 10:04

Jaspal


People also ask

How can an inner class access the members of outer class?

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.

How do you call an outer class from an inner class?

Of your inner class is non static then create an object of innerClass. OuterClass out = new OuterClass(); OuterClass. InnerClass inn = out.

How do you access class members on Kotlin?

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.

How do you access the variables of an outer class?

You can access the static variable of an outer class just using the class name.


Video Answer


2 Answers

You should mark class B as inner:

class A{
  var name: String

  inner class B{
    fun show(){
      print(name)
    }
  }
}
like image 100
Eric Martori Avatar answered Sep 21 '22 08:09

Eric Martori


Use like this

class A{
lateinit var name: String

inner class B{
    fun show(){
        print(name)
    }
}
}
like image 21
sasikumar Avatar answered Sep 19 '22 08:09

sasikumar