Kotlin: Constructor of inner class nested can be called only with receiver of containing class


#1

Hi, I’m have created nested class but now i can’t access it properly its giving me error i have tried addiing keyword

Public

it didn’t work i don’t know where i’m wrong when checking from kotlin original website i found this code.

//Code from the kotlin website
        class Outer {
            private val bar: Int = 1
            inner class Inner {
                fun foo() = bar
            }
        }

    val demo = Outer().Inner().foo() // == 1

i did same kind of thing but with String but my code is giving me error.
//My Code

class Outer{

    private val name:String?=null

    inner class Nested{
         fun show(){

            println("Nested")
            //println(name) this won't run until we add word "inner" with nested class

            //now we have added inner now "name" can be accessed
             println(name)

        }
    }

}

fun main(args:Array<String>){

    var obj = Outer() //outer class instance created
    val obj2 = Outer.Nested() //Here instance of nested class in created
    obj2.show()
}

When i don’t use keyword inner with the Nested class then its working fine but without it its not working can someone please explain it a bit thanks.

Error:

Error:(23, 22) Kotlin: Constructor of inner class nested can be called only with receiver of containing class


#2

https://kotlinlang.org/docs/reference/nested-classes.html#inner-classes

A class may be marked as inner to be able to access members of outer class. Inner classes carry a reference to an object of an outer class

Therefore you have to call the constructor of an inner class like this

Outer().Nested()

otherwise the inner class could not store a reference to the outer class.


#3

Thanks a lot for your help i got it thanks.