Immutable objects and constructor ?
chmike via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri May 20 07:06:54 PDT 2016
I'm implementing the flyweight pattern. It means that I have a
set of object instances representing all the possible values.
This allows me to manipulate "values" by simply manipulating
references to the instance. Testing "value" equality boils down
to simply compare reference value. I hope I can use these
immutable instances as case argument of a switch, but I'm not
there yet.
I have declared an immutable class.
----
immutable interface SomeInfo { ... }
immutable class Info : SomeInfo {
@disable this();
this(int codeValue, string codeName)
{
codeValue_ = (codeValue * 10) - 113; // some random
example computation
codeName_ = "Info."~codeName_;
}
private:
int codeValue_;
string codeName_;
}
----
But when I try to instantiate the class I get an dramatic
compilation error:
"none of the overloads of '__ctor' are callable using a mutable
object, candidates are: "
Adding immutable to the constructor doesn't help. How can I
initialize the immutable instances of a class ?
I have seen it is possible to cast away the immutability. Does it
also work for immutable classes ? Could I use an object factory ?
How should I do if I would like to use the lazy pattern for
initializing some member variables of the instance ? Something
like :
immutable class Info : SomeInfo
{
...
string toString()
{
if (!toString_)
synchronize { // make it thread safe
if (!toString_)
toString_ = format("bla bla %s (%d)", codeName_,
codeValue_);
}
return toString_;
}
...
private:
string toString_;
}
More information about the Digitalmars-d-learn
mailing list