lazy construction of an immutable object

Puming via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 15 03:39:41 PDT 2014


Hi,

I'd like to use immutable data, but instead of a one time 
constructor, I would like to `build` the data lazily, by setting 
its fields separately.

In java version of protocol-buffer, there is a pattern for this 
mechanism:

1. Every data class in protobuf is immutable.
2. Each data class is companioned by a Builder class, with the 
same field of the immutable data class.
3. To create a data object, first create a Builder, then set the 
fields when ever you want.

I want to emulate this process, but without needing to create two 
classes for one data class (protobuff does this by a separate 
code generating phase to generate both classes from a data format 
file).

What is the idiomatic approach to do this in D?

if I define a class with immutable fields, like

```d
class A {
   immutable int id;
   immutable B b;
}
```

should I use a template to generate the companion Builder class, 
or is there another aproach?



More information about the Digitalmars-d-learn mailing list