Calling member functions of immutable classes
-
25-06-2021 - |
Question
immutable class Foo
{
void bar()
{
}
}
void main()
{
auto x = new Foo();
x.bar();
// Error: function test.Foo.bar () immutable is not callable
// using argument types ()
}
What do I have to change in the program so that x.bar()
compiles? Does x
have the wrong type?
Solution
Looks like a bug. x
is inferred to have the type Foo
, which although is an immutable class, it is treated as if a mutable variable, which caused x.bar()
to fail because bar()
is an immutable method.
A workaround is to provide an empty immutable constructor function,
immutable class Foo
{
void bar()
{
}
immutable this() {} // <---
}
which caused the new Foo()
expression to return an immutable(Foo)
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow