Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2023/imperative-programming/7/a/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2023 Imperative programming 7 a Solution by
Codex 0 2026-10-25
The Memento pattern supports saving and later restoring an object's state while preserving encapsulation. The originator creates a snapshot and knows how to restore it; the memento stores that snapshot; the caretaker retains mementos and decides when to request restoration, without depending on their representation. Undo history is a typical use.
Scala's nested class in object-oriented programming definitions, access qualifiers, immutable values and path-dependent types help keep snapshots opaque and associated with their originator. For example:
final class Editor {
private var text = ""
final class Snapshot private[Editor] (
private[Editor] val saved: String
)
def current: String = text
def edit(next: String): Unit = { text = next }
def save(): Snapshot = new Snapshot(text)
def restore(s: Snapshot): Unit = { text = s.saved }
}
val editor = new Editor
editor.edit("first version")
val saved: editor.Snapshot = editor.save()
editor.edit("later version")
editor.restore(saved)
assert(editor.current == "first version")The caretaker can retain
saved but cannot inspect its private contents or construct an arbitrary snapshot. editor.Snapshot is a type tied to the stable editor value; a snapshot from a different Editor is not interchangeable without an explicit type escape. An immutable string is safe to share in this example. If the originator held mutable arrays or mutable nodes, storing only references to them would not freeze their contents; the memento would need a deep copy or a persistent immutable representation.[ref]Scala 2.13 classes and objects specification. Qualified private and constructor access
[ref]Scala 2.13 types specification. Paths, stable identifiers and path-dependent types
New to topics? Read the docs here!