Very confusing error message when calling a class method from an invariant

Paul Backus snarwin at gmail.com
Wed Mar 10 04:57:19 UTC 2021


On Wednesday, 10 March 2021 at 03:39:15 UTC, Meta wrote:
> class Human {
>     static immutable MAX_AGE = 122;
>
>     bool alive = true;
>     int age = 0;
>     //Error: mutable method onlineapp.Human.checkAge is not 
> callable using a const object
>     invariant(checkAge());
[...]
>
> What the hell does this even mean, and where does it come from? 
> Adding `inout` to `checkAge` actually does cause it to compile 
> and run too. WTF?

 From the language spec [1]:

> The invariant is in the form of a const member function.

So, inside the invariant, the object is treated as const, which 
means you can't modify it and can only call const methods.

[1] https://dlang.org/spec/class.html#invariants


More information about the Digitalmars-d-learn mailing list