Solution (source code)

= Solution

For the implementations above, the output is
``
0
1
``
In `A`, the <Scala trait linearization> sends `insert('a',0)` first to `CapitalisePlugIn`, then to `CharTrackPlugIn`, then to `DocImpl`. The counter <trait> receives `'A'`, so it does not increment the lowercase `'a'` count. The stored document is `A`.

In `B`, the counter <trait> receives `'a'`, delegates through `CapitalisePlugIn`, and increments its original argument's counter on return. The stored document is again `A`, but the counter records one lowercase insertion:
$$
\boxed{\mathrm{d1.getCount('a')}=0,\qquad\mathrm{d2.getCount('a')}=1.}
$$
This demonstrates a composition that violates the count-of-current-document <representation invariant> for `B`: an earlier counter cannot assume a later transforming <trait> inserts its argument unchanged. Subsequent deletion also receives uppercase `'A'` and would leave that stale lowercase count. A different valid design could inspect `read(pos)` after insertion to count the actual stored character; that design would produce `0,0`. The stated `0,1` follows the explicit implementation in part (b), whose correctness assumption has now failed in the second composition.