Reputation: 1833
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.
Upvotes: 26
Views: 18059
Reputation: 2394
The easiest way would be to place the definition of your InnerClassX
outside of the sealed InnerClassSuper
, then the InnerClassX
will become an inner class of OuterClass
and will be able to be instantiated and to reference its members:
class OuterClass {
fun someFun(): InnerClassSuper {
return InnerClassX("Hello") // this is legit now
}
sealed class InnerClassSuper
inner class InnerClassX(val x: String): InnerClassSuper()
}
Upvotes: 1
Reputation: 527
We can use it this way too
OuterClassName().NestedClassName()
Upvotes: 26
Reputation: 148089
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")
}
}
Upvotes: 10