Group Group Group Group Group Group Group Group Group

Sealed Classes Example

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?

Thanks for the question @chuck_taylor!

You mentioned “When I try to call that function as exemplified circle1.size I get Unresolved Reference errors.” The reason for that, with the code as written in the book, is that size() is not a method on the Shape enum class, it’s just a stand-alone function. So you would call it like this:

size(circle1)

I think that is what you were missing. Thanks again for the question!