Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I was trying inner classes in Kotlin and came across this error but didn't quite understand it. I tried to look at the documentation here but didn't quite get any direction as to how outer classes can access inner class constructors

class OuterClass {

  fun someFun(): InnerClassSuper {
    return InnerClassX("Hello") //Error: Constructor of inner class InnerClassX can be called only with receiver of containing class
  }

  sealed class InnerClassSuper {

    inner class InnerClassX(val x: String): InnerClassSuper()

  }
}

Would appreciate if someone explains the error and directs how to fix it. Thanks.

like image 666
Pravin Sonawane Avatar asked May 15 '18 17:05

Pravin Sonawane


2 Answers

We can use it this way too

OuterClassName().NestedClassName()

like image 164
shivambhanvadia Avatar answered Sep 20 '22 23:09

shivambhanvadia


Your code basically means that InnerClassX is an inner class of InnerClassSuper, not OuterClass, so the error means you need to provide a receiver object of InnerClasssSuper upon construction of InnerClassX.

At this point, Kotlin allows having neither an inner sealed class nor a derived class for a sealed class as an inner class of another class.

You can, however, make an abstract class derived from the sealed one and inherit from it inside the OuterClass:

sealed class SealedClassSuper {
    abstract class SealedClassChild(val x: String): SealedClassSuper()
}

class OuterClass {
    inner class InnerClassX(x: String) : SealedClassSuper.SealedClassChild(x)

    fun someFun(): SealedClassSuper {
        return InnerClassX("Hello")
    }
}
like image 43
hotkey Avatar answered Sep 18 '22 23:09

hotkey