Sealed classes - would you want them in D?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu May 10 21:26:12 UTC 2018


On Thursday, May 10, 2018 13:22:20 Piotr Mitana via Digitalmars-d wrote:
> Hello,
>
> I've recently thought of sealed classes (sealed as in Scala, not
> as in C#) and am thinking of writing a DIP for it. I decided to
> start this thread first though to gather some opinions on the
> topic.
>
> For those who never coded Scala and don't know sealed classes: a
> sealed class is a class which can be only extended in the same
> source file.
>
>      sealed class MyClass {}
>
> Translating to D, a sealed class would could only be extended in
> the same module. Additionally I would suggest
> "sealed(some.package) MyClass {}" syntax for classes that could
> only be extended in the particular package.
>
> In Scala an important value of sealed classes is that compiler
> knows that and can aid programmer in pattern matching by
> detecting the missed cases. However, there is another value I
> see: limiting the extension of classes.
>
> Some time ago I was working on a simple CQRS library and created
> an Entity class, where I wanted only a few specific subtypes for
> it. The library is built over a few defined entity types and user
> is not able to create their own types (should extend the
> particular subtype instead). Sealing the Entity class could
> enable me to define the closed set of subtypes and prevent new
> direct subtype creation outside the library.
>
> Combining sealed with final library developer can create a
> completely closed type hierarchy.
>
> Any thoughts on that proposal?

I think that the main thing is that the use case has to be strong enough to
merit complicating the language further by adding such a feature, and I
really don't know if the use case is really all that strong. My gut reaction
is that it's catering to a very specific and rare use case and as such would
not be worth adding, but I don't know. Idiomatic D tends to use classes
rarely, and I can't think of any situation where what you're describing
would ever have been useful to me, but that doesn't necessarily mean that
some people wouldn't find it really useful, and depending on how much value
it adds in such situations, it might be worth adding. Ultimately though, I
think that if you want to create a DIP for something like this, you're going
to need some very strong use cases where this is solving a real problem and
why the current situation is lacking. If it's a significant improvement in
enough situations, then you'll probably be able to get a DIP accepted, but
if it's just helping in some rare cases, I'd expect it to stand a low chance
of acceptance. Nothing stands out to me about the idea as being
fundamentally bad though.

- Jonathan M Davis



More information about the Digitalmars-d mailing list