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.
We can use it this way too
OuterClassName().NestedClassName()
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")
}
}
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