Top-level sealed class subclasses

I am struggling with the following restriction for sealed classes:

A sealed class can have subclasses, but all of them must be nested inside the declaration of the sealed class itself.

I try to only use a nested class if its sole purpose is to serve its enclosing class. This is discussed in Effective Java, Second Edition, Item 22:

A nested class should exist only to serve its enclosing class.

Perhaps I’m simply doing it wrong but it seems to me that I shouldn’t have to use nested classes in order to implement sublcasses for my sealed class. I understand that there needs to be some way to limit inheritors of the sealed class though.

Consider the following sealed class and subclasses:

package com.example.boxmodel

sealed class Box(/*...*/) {
    class Block(/*...*/) : Box()
    class InlineBlock(/*...*/) : Box()
    class Inline(/*...*/) : Box()
    class Marker(/*...*/) : Box()
}

Could the restriction be made that the subclasses need to be in the same file? e.g.:

package com.example.boxmodel

sealed class Box(/*...*/)
class BlockBox(/*...*/) : Box()
class InlineBlockBox(/*...*/) : Box()
class InlineBox(/*...*/) : Box()
class MarkerBox(/*...*/) : Box()

Or perhaps in the same module even or by some other means so that we don’t have to nest them?

This is coming in 1.1.

Excellent! I couldn’t find mention of it anywhere. Thank you @pniederw1. I’m guessing there is an issue in YouTrack to track this but I couldn’t find it.

1 Like