Private nested class instance accessed via outer class public interface

Anonymouse zorael at gmail.com
Fri Jun 16 09:37:54 UTC 2023


On Friday, 16 June 2023 at 07:47:50 UTC, Murloc wrote:
> And since classes can be declared locally inside methods, you 
> can also do something similar this way:
>
> ```d
> import std.stdio;
> import std.conv;
>
> Object getB() {
>     class B {
> 		private int field = 30;
>         override string toString() => to!string(field);
> 	}
>     return cast(Object)new B();
> }
>
> void main() {
>     auto b = getB();
>     writeln(b); // 30
> }
> ```

This isn't fully playing to its strengths either, there's no need 
to cast it to Object if you declare the return type to be `auto`.

```
import std.stdio;
import std.conv;

auto getB() {
     class B {
         private int field = 30;
         override string toString() => to!string(field);
     }
     return new B();
}

void main() {
     auto b = getB();
     writeln(b); // 30
}
```

I use it a lot like so:

```
import std;

auto getThing()
{
     struct Thing
     {
         int x, y;
         double weight;
         int fluffiness;
     }

     Thing thing;
     thing.x = 42;
     thing.y = 128;
     thing.weight = 99.9;
     thing.fluffiness = 9001;
     return thing;
}

void main()
{
     //Thing thing;  // Unidentified identifier Thing
     auto thing = getThing();
     writeln(typeof(thing).stringof);  // Thing
     writeln(thing);  // Thing(42, 128, 99.9, 9001)
}
```

https://wiki.dlang.org/Voldemort_types


More information about the Digitalmars-d-learn mailing list