# 3.13 immutable and snapshot

> `snapshot` takes a complete picture of a value and returns it as `immutable`: everything can be read, but nobody can change it.

Web page: https://pseudolearn.app/en/spec/tipos/inmutable

> **In one sentence**
>
> `snapshot` takes a complete picture of a value and returns it as `immutable`: everything can be read, but nobody can change it.

## 3.13.1 How it works

Vectors, dictionaries and arrays are shared: if someone modifies them, everyone sees it. Sometimes the opposite is needed, a value that **cannot** change. `snapshot(x)` copies `x` whole, with everything it contains, and returns an `immutable` of that type.

### Program: A picture that does not change

```pseudolearn
Algorithm Congelar
  Define notas As Vector<Integer> <- vector();
  notas.append(7);
  Define foto As Immutable<Vector<Integer>> <- snapshot(notas);
  notas.append(9);
  Write foto.length(), " ", notas.length(), " ", foto[0];
EndAlgorithm
```

**Output**

```text
1 2 7
```

*The program finishes normally.*

**Figure 3.13-1: The snapshot does not change**

The vector notas held a 7 when the snapshot was taken; a 9 was added afterwards. The picture, with a padlock, keeps only the 7: it can be read but not written.

The snapshot copies the whole content. Whatever happens to the original afterwards does not affect the picture.

An `immutable` allows every read, but no write and no modifying method:

### Program: Trying to change the picture

```pseudolearn
Algorithm EscribirFoto
  Define notas As Vector<Integer> <- vector();
  Define foto As Immutable<Vector<Integer>> <- snapshot(notas);
  foto.append(9);
EndAlgorithm
```

**Diagnostics**
- `immutableValueWrite` (error, 4:3): An immutable value cannot be modified

*The program finishes with an error.*

## 3.13.2 Why it exists

Concurrent tasks cannot share vectors or dictionaries, because two tasks could change them at the same time. An `immutable` can cross between tasks: since nobody modifies it, sharing it is safe.

> **Limit**
>
> - `snapshot` accepts primitives, enumerations, records, variants, vectors, dictionaries and arrays, and copies deeply keeping internal aliases.
> - It does not accept class objects or functions: `snapshotNotSupported`.
> - The copy counts towards the engine's memory limit.
> - `copy` makes a shallow copy and gives no immutability.

**In short**
- `snapshot(x)` copies everything and returns an `immutable`.
- An `immutable` is read but not modified.
- Whatever the original changes afterwards does not affect the snapshot.
- Immutables can move from one task to another.

**See also**
- [11.2 Task scopes with Tasks and Spawn](https://pseudolearn.app/en/spec/tareas/ambitos.md)
- [9.6 Copies, references and identity](https://pseudolearn.app/en/spec/objetos/copia.md)
