8: Type Mutability [✓] - royal-lang/rl GitHub Wiki

Types in Royal are mutable by default but immutability can be set as default for a module by using the immutable keyword in the beginning of the module.

Example:

module mymodule;

immutable:

// Everything below is immutable.

You can escape the mutability by using the mut keyword.

module mymodule;

immutable:

var int immutableInt;
var int immutableInt2;

var int:mut mutableInt;

mut:

// Everything below is mutable.

There are 3 different mutabilities in Bausslang.

Mutable, Immutable and Const.

  • Const types can be converted to immutable.

  • Mutable types can be converted to immutable if they're not reference types or if they are copied.

  • Both mutable and immutable types can be converted to const.

  • Neither immutable or const types can be converted to mutable.

  • Immutable types can only be initialized in constructors by value types or local non-escaped reference types.

  • Const types can be initialized anywhere.

  • Mutable types can be initialized anywhere.

  • Immutable types are guaranteed not to ever change and cannot have any mutable reference to them.

  • Const types may be changed from a mutable reference to the same type but the const type itself cannot be changed.

  • Mutable types have no change guarantees.

Const and immutable types will have all members down their tree const and immutable as well. This is a design choice and ensures type-safety. This is different from C++ where you can have a const pointer to a mutable pointer etc. that is not possible in Royal.

Mutability for a type is specified using the : symbol.

TYPE:MUTABILITY

Example:

var int:immutable i = 100;

i = 200; // Error ...

var int:const i2 = i;

var int i3 = i2; // Error ...

var int[]:immutable immutableArray = [1,2,3];

// Actual representation of "string" in Royal:
alias string = char:immutable[];
// Which means: A dynamic array of immutable chars.