-
-
Notifications
You must be signed in to change notification settings - Fork 4
mutable
Auto edited this page Oct 5, 2021
·
8 revisions
There are two kinds of mutability:
- mutable variables can point to different objects during their lifetime.
- mutable objects can change during their lifetime.
x="hello"
x+=" world" # ok, value was mutable
x="bye" # ok, variable was mutable
- immutable variables point to the same object during their lifetime.
- immutable objects stay completely unchanged during their lifetime.
The first variant is called 'let' variable:
final x="hello"
val x="hello"
let x="hello"
x+=" world" # ok, value was mutable
x="bye" # error: variable was immutable
Both properties can be combined with the constant
keyword or with the := sigil:
constant x = "hello"
x := "hello" # ok redundant redeclaration
x+="ok" # error: immutable value
x="hi" # error: constant variable
See keyword 'constant' on how to finetune semantics.
This is near identical to JavaScript's:
Uncaught SyntaxError: Identifier 'x' has already been declared
Uncaught TypeError: Assignment to constant variable.
The differences being:
- In Angle it is allowed to re-declare a variable IF the value is identical.
- In JavaScript it is allowed to modify the values of constant variables
- In JavaScript it is allowed to re-declare variables without let:
const x=7
x=7 # ok in Angle, error in JS
const y=[1,2,3]
y.remove(1) # ok in JavaScript, error in Angle
[ 2, 3 ]
let x=1
x=2 # ok in JavaScript
let x=2 # error
Immutable lists are equivalent to tuples in other languages and can be defined as such:
immutable a=(1,2,3)
const b=(1,2,3)
tuple c(1,2,3)
a==b==c