Solution (source code)

= Solution

Keep a running total in the <mixin>, and use only the inherited public operations. Updating after a successful superclass operation leaves the total unchanged if an empty `pop` fails its <precondition>.
``
trait SumPlugin extends Stack {
  private var total = 0

  override def push(x: Int): Unit = {
    super.push(x)
    total += x
  }

  override def pop(): Int = {
    val x = super.pop()
    total -= x
    x
  }

  def sum: Int = total
}
``
For this <trait> mixed directly into `Stack`, its <representation invariant> is $total=\sum s$, where $s$ is the abstract <stack> <sequence>. A successful push adds exactly its argument and a successful pop removes exactly its returned value. Thus
$$
\boxed{sum=\text{the sum of the current stack entries},\qquad sum(\text{empty stack})=0.}
$$
The <mixin> reads no private `Stack` fields. Its operations add constant <time complexity>. As in the paper's `Int` interface, an unbounded mathematical total requires excluding <integer overflow>, or replacing the accumulator with `BigInt` if the interface is allowed to change. A later <mixin> can transform a pushed value at a different point in the <Scala trait linearization>; the effect is analyzed in the next part.