Sealed classes - would you want them in D?

Walter Bright newshound2 at digitalmars.com
Sat May 12 10:27:11 UTC 2018


On 5/11/2018 4:27 PM, H. S. Teoh wrote:
> On Fri, May 11, 2018 at 04:14:43PM -0700, Walter Bright via Digitalmars-d wrote:
>> On 5/10/2018 6:22 AM, Piotr Mitana wrote:
>>> 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.
>>
>>    private class MyClass { }
>>
>> should do the trick.
> 
> It doesn't; if you do this, you can't pass MyClass outside the module
> and have other modules invoke its methods.  They will get an essentially
> opaque object.  You'll have to resort to ugly wrapper types (defined in
> the same module) in order to make this work.

The solution is:

     private class MyClass { ... }
     public final MyClassSealed : MyClass { }

Meaning other modules can use MyClassSealed but cannot derive from it. Other 
classes inside the module can derive from MyClass as required.


More information about the Digitalmars-d mailing list