Named constructors
    Arafel 
    er.krali at gmail.com
       
    Sat Nov  9 12:35:47 UTC 2024
    
    
  
On 9/11/24 1:02, JN wrote:
> ```d
> class Angle
> {
>      float radians;
> 
>      this.fromRadians(float rad) : radians(rad) { }
>      this.fromDegrees(float degs) : radians(degs * (PI / 180.0f)) {}
> }
> 
> Angle a1 = new Angle.fromRadians(PI / 2.0f);
> Angle a2 = new Angle.fromDegrees(90.0f);
> ```
This would interfere with, and can be simulated through, nested classes:
```d
enum PI=3.141592f;
class Angle
{
     float radians;
     this(float rad) { radians = rad; }
     static class FromRadians : Angle {
         this(float rad) { super(rad); }
     }
     static class FromDegrees : Angle {
         this(float degs) { super(degs * (PI / 180.0f)); }
     }
}
void main() {
	Angle a1 = new Angle.FromRadians(PI / 2.0f);
	Angle a2 = new Angle.FromDegrees(90.0f);
}
```
If you don't want to allow direct instantiations of `Angle`, you can 
declare it `abstract`, or disable its constructor.
    
    
More information about the dip.ideas
mailing list