You are here :

Sub nodes

Recent changes
Site plan

Constness is a way to make variables immutables ... ie, a variable that cannot be assigned.

Arguments, variables, fields, methods can be const.

Example :

 public SomeClass {
   static private const int i = 0; // a const field
   // a const argument
   public constructor(const int j) {
   public sub f() {
     const int j = i; // a const variable
   // a const method
   public sub g() const {

When arguments/variables/fields are declared const, that means they cannot be modified. When a method is declared const that means it does not modify the state of the instance => all fields are treated as const fields : they cannot be modifiable.


As in c++, one can use the 'mutable' keyword to render a field modifiable in a const method. Care must be taken when using this feature. Usually, using 'mutable' means an 'implementation detail'. That means you usually have to think 'is the method really const from the interface and from the instance ?' If the answer is yes and you have to render a field mutable it is likely you're right. If you render a method non const whereas from the interface/instance it should be const you have a problem.

Syntax :

 [public | protected | private] mutable TypeName fieldName;

Example :

 public primitive class date {
   mutable int days;
   mutable bool validDays;
   int day;
   int month;
   int year;
   constructor(int day, int month, int year)
     validDays = false; = day;
     this.month = month;
     this.year = year;
   constructor(int days)
     validDays = true;
     this.days = days;
   public int days() const {
     if (!validDays)
       days = dmyToDays(day, month, year);
     return days;

In this case, the days() method is really read-only : it should be const. The fact that we perform a lazy evaluation (we transform day, month, year to days only on demand) is a detail of implementation : the mutability of field days is justified.

Propulsed by Wiclear