Non-ugly ways to implement a 'static' class or namespace?

Ruby The Roobster rubytheroobster at yandex.com
Fri Jan 20 12:55:37 UTC 2023


On Friday, 20 January 2023 at 11:28:23 UTC, thebluepandabear 
wrote:
> Hi,
>
> In Java/C# you can create purely static classes.
>
> These are classes whose methods are all static, the classes 
> cannot be derived from or instantiated:
>
> ```
> static class Algo {
>     void drawLine(Canvas c, Pos from, Pos to) { ...... };
> }
> ```
>
> Class in use:
>
> ```
> Algo.drawLine(new Canvas(), new Pos(5, 3), new Pos(7, 9));
> ```
>
> This type of semantics is not possible in D, which sucks.
>
> After scouring the forums, the only workaround seems to be the 
> following:
>
> ```
> final abstract class Algo {
>     void drawLine(Canvas c, Pos from, Pos to) { ...... };
> }
> ```
>
> This solution seems like a bit of a hack, which is why I don't 
> like it.
>
> Alternatively you could create a module, but then it would just 
> be a function without a clear type.
>
> Is anyone aware of a non-ugly way to implement a 'static' class 
> or namespace?
>
> Regards,
> thebluepandabear

There is no way to implement that functionality in D.  `final` 
means that the class cannot be extended, and `abstract` requires 
that only an extension of said class can be instantiated.  
However, unlike in Java and C#, you cannot call a function 
without instantiating said class, as functions act on the class 
object.


More information about the Digitalmars-d-learn mailing list