lazy construction of an immutable object
Puming via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jul 15 08:48:09 PDT 2014
On Tuesday, 15 July 2014 at 13:59:24 UTC, Ali Çehreli wrote:
> On 07/15/2014 05:20 AM, Puming wrote:
>> 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.
>
> Also consider: A pure function's return value can implicitly be
> converted to immutable.
>
> class A
> {
> int x;
> int y;
>
> this (int x) pure
> {
> this. x = x;
> }
> }
>
> pure A makeA(int x) // <-- returns mutable
> {
> auto a = new A(x);
>
> // ...
> // Set a member later on:
> a.y = 42;
>
> return a;
> }
>
> void main()
> {
> immutable imm = makeA(1); // <-- works
> }
>
> Ali
wow, that's interesting :-) Is it the idiomatic approach to
initiate immutable objects lazily? Or do people use data class
with immutable fields and generate a companion builder class at
compile time?
More information about the Digitalmars-d-learn
mailing list