I’m not understanding the example code found on page 238
Specifically, the code block under “And functions defined on Shape can distinguish between the different subtypes using a when expression:”
fun size(shape: Shape): Int {
return when (shape) {
is Shape.Circle -> shape.radius
is Shape.Square -> shape.sideLength
}
}
circle1.size // radius of 4
square2.size // sideLength of 2
When I try to call that function as exemplified circle1.size
I get Unresolved Reference errors. When I move that function inside the sealed Shape class as a method, I still get errors as the IDE is expecting the arguments for shape
in the function. I ended up adjusting the code as follows and placed it inside the Shape sealed class as a method:
fun size(): Int = when (this) {
is Shape.Circle -> this.radius
is Shape.Square -> this.sideLength
}
At least now I can call is like so
circle1.size()
However, am I missing something? This is apparently the reason why someone would want to use a sealed class?