Search code examples
kotlinconstructorinner-classes

"Constructor of inner class can be called only with receiver of containing class" when I create inner classs instance in constructor


I have a class

data classOuter (
    val str: String = "fOo"
    ...
    val innerClassInstance: InnerClass= InnerClass(),
) {

  ...
  inner class InnerClass {
     fun foo () {     
         return str.toLowerCase()
     }
  }
}

But I get an error:

Constructor of inner class InnerClass can be called only with receiver of containing class

Is there way to avoid it ?


Solution

  • There is chicken and egg problem. Inner class object refers parent class object, which is not yet constructed at this point (at the point of passing parameters to the constructor of parent class).

    You may employ lazy initialisation of nested class object, so it would be initialised at the time parent class object already exists. Like:

    data class classOuter (
        val str: String = "foo"
    ) {
      val innerClassInstance: InnerClass by lazy { this.InnerClass() }
    
      inner class InnerClass {
         fun foo () : String {     
             return str.toLowerCase()
         }
      }
    }
    
    fun main() {
        println(classOuter("bar").innerClassInstance.foo())
    }