Confused About Const Classes?7th March 2014

const classes are mentioned a lot in Fantom, especially in the topics of IoC and services. const classes are defined by the const keyword and look like this:

constclass MyClass {const Int? value
}

But what makes it different to a standard non-const class?

class MyClass {
Int? value
}

I shall explain.

In a nut shell, const classes are immutable. That is:

Once created, the data they hold can never change!

Now, just like any other class, a const class holds its data in fields. But, to make sure everyone knows the field values can never change, they too, must be defined with the const keyword. And now, that value is constant. In fact, it's a compilation error to even attempt to change it!

Maps and Lists

But what of Maps and Lists? These may not be const but they can still be used in const classes because they're special. Maps and Lists have the concept of being immutable. As soon as you assign them to a const field, their contents are locked down and can never change again. No other Fantom class can do this, not even your own classes, that's why they're special.

constclass MyClass {const Str[] constList := ["wot", "ever"]}

Nice, now what if you want to generate list data on the fly and set it in the ctor? Well, there's a right way and a wrong way. This is the wrong way to add data to a const List:

Advanced - The it-block ctor

The first thing to notice is No Compilation Err! The const fields are not set in the ctor, yet Fantom doesn't complain. That's because Fantom is anticipating what's coming next!

We can create an instance of MyClass by passing in a block, which takes MyClass (or This) as an argument. The f(this) executes the block, passing in itself as the argument. Fantom is expecting this block to set the const fields.