lazy construction of an immutable object
Puming via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jul 15 05:20:56 PDT 2014
I found another way to do this, namely first create a class that
is mutable, then cast it to an immutable object before using it.
```d
class A {
int a;
B b;
this(int a, int b)
{
this.a = a;
this.b = new B(b);
}
}
class B {
int b;
this(int b)
{
this.b = b;
}
}
@property immutable(T) freeze(T)(T obj)
{
return cast(immutable(T))(obj);
}
void main()
{
immutable c = new A(3, 4).freeze;
c.b.b = 5; // Error: can only initialize const member b inside
constructor
writeln(c.b.b)
}
```
But the draw back is that you can't garanteed that the mutable
object is never used.
On Tuesday, 15 July 2014 at 10:39:42 UTC, Puming wrote:
> 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