2.3 How to make an object with read only properties?

(added March 23, 2026)

Maple does not directly support this but can be done manually.

The idea is this: We want to make an object with a local property, say the name of the person, where this field can be read from outside the object directly but can not be changed. To change it, we must call the set method on the object.

This makes the object behave like a standard record or struct, where fields can be read directly, but with the added benefit is these fields can not be modified unless the object setter method is called.

To do this, we have to make the field exported but add protection on it. Anytime an object method is called, the internal method has to remove the protection, make any changes, then set the protection on the field back on.

Here is an example

foo := module() 
option object; 
export A; 
export B; 
 
local protect_all::static:=proc(_self,$) 
      protect('_self:-A'); 
      protect('_self:-B'); 
end proc; 
 
local unprotect_all::static:=proc(_self,$) 
      unprotect('_self:-A'); 
      unprotect('_self:-B'); 
end proc; 
 
#this is the constructor, which is called once to make the object 
export ModuleCopy::static := proc(_self :: foo, proto :: foo, A, B, $) 
        _self:-A := A; 
        _self:-B := B; 
        _self:-protect_all(); 
    end proc; 
 
export set_A::static:= proc(_self,A,$); 
        _self:-unprotect_all(); 
        _self:-A := A; 
        _self:-protect_all(); 
    end proc; 
 
protect(A); 
protect(B); 
end module:
 

To use it do

o:=Object(foo,10,20); 
                  o := Object<<2708752886816>> 
o:-A; #read value 
                               10 
o:-B; #read value 
                               20 
 
o:-A:=10 #try to change it, now gives error. Good 
 
Error, attempting to assign to `A` which is protected.  Try declaring `local A`; see ?protect for details. 
 
o:-set_A(99);  #to change value we must call its set method 
 
o:-A; #this shows value changed 
                               99 
 
o:-B; 
                               20
 

The advantage of this, is that we can easily read values from the object, as it was a struct but get the protection benefits of using an object.