Enforced immutability: Difference between revisions

Added Wren
m (→‎{{header|Raku}}: Fix comments: Perl 6 --> Raku)
(Added Wren)
Line 1,178:
Pi:= 3.15; \causes a compile error: statement starting with a constant
</lang>
 
=={{header|Wren}}==
In Wren, instance and static fields of a class are always private and cannot be mutated unless you provide 'setter' methods for that purpose.
 
In addition instances of the built-in Num, Bool, String, Range and Null classes are always immutable.
 
Other than this, there is no way to create immutable values (nor constants for that matter) in Wren.
 
The following example shows a simple class A which has a single field _f. Access to this field is controlled by getter and setter methods 'f' and 'f='. Without the setter, instances of A would be effectively immutable.
 
Note though that if fields are reference types (lists, maps, user-defined classes etc.) even a 'getter' method may enable their internal state to be mutated unless you copy them first.
<lang ecmascript>class A {
construct new(f) {
_f = f // sets field _f to the argument f
}
 
// getter property to allow access to _f
f { _f }
 
// setter property to allow _f to be mutated
f=(other) { _f = other }
}
 
var a = A.new(6)
System.print(a.f)
a.f = 8
System.print(a.f)</lang>
 
{{out}}
<pre>
6
8
</pre>
 
=={{header|zkl}}==
9,476

edits