You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/_docs/reference/experimental/capture-checking/mutability.md
+31Lines changed: 31 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -339,3 +339,34 @@ The subcapturing theory for sets is then as before, with the following additiona
339
339
-`{x, ...}.RD = {x.rd, ...}.RD`
340
340
-`{x.rd, ...} <: {x, ...}`
341
341
342
+
## The `immutable` Wrapper
343
+
344
+
We often want to create a mutable data structure like an array, initialize by assigning to its elements and then return the array as an immutable type that does not
345
+
capture any capabilities. This can be achieved using the `immutable` wrapper.
346
+
347
+
As an example, consider a class `Arr` which is modelled after `Array` and its immutable counterpart `IArr`:
The `immutable` wrapper allows us to go from an `Arr` to an `IArr`, safely:
358
+
```scala
359
+
importcaps.immutable
360
+
361
+
valf:IArr[String] =immutable:
362
+
vala=Arr[String](2)
363
+
a(0) ="hello"
364
+
a(1) ="world"
365
+
a
366
+
```
367
+
The `immutable` method is defined in `caps` like this:
368
+
```scala
369
+
defimmutable[T](op: ->T):T= op
370
+
```
371
+
It takes a pure by-name parameter and returns its result. But the actual return type after capture checking is special. Instead of just `T` as in the declaration above suggests, it's `T` where every covariant occurrence of a `Mutable` type gets its capture set mapped to `{}`.
0 commit comments