Skip to content

(compiler) Add support for immutable fields

Per Lundberg requested to merge feature/add-immutable-field-support into master

The nice part about this is the syntax. While not claiming it to be perfect in any way, I like the idea of "reversing" the const keyword from other languages - let const be the default and mutable be the slightly more awkward, opt-in. The idea is of course to encourage people to design systems with an immutability-first mindset.


Copying content from !583 (comment 3757), for better visibility

There we go. This took quite an effort but this now adds:

  • Support for immutable fields
  • Support for traversing property paths such as foo.bar.baz. Because our fields are private, that exact example does not work but the important part is that things like this.name works as expected (and does not clash with local variables or parameters named name)
  • Validating that immutable fields are only set using an initializer or in all defined constructors.
  • Validating that immutable fields set using an initializer are not modified in any constructor.
  • Validating that all properties are properly set after each constructor returns.
    • Note that we currently do not have any default values for fields (as is the case in C# with default(T), initializing all reference types to null, all int values to 0 etc); we are more akin to Java in that sense. The user must explicitly initialize all fields to an explicit value, either by using a field initializer or an assignment in the constructor.

As implied by the above, this was a bit non-trivial so I'm happy to see that it now seems to be done. 🎉

Edited by Per Lundberg

Merge request reports

Loading