Memento pattern 2026-10-24
A design in which an originator creates an opaque snapshot of its state, a caretaker retains it, and the originator can later restore it. Encapsulation prevents the caretaker from depending on internal state representation. A memento must freeze the relevant state: references to mutable objects can require a deep copy, while immutable values can safely be shared. Scala's access controls and path-dependent types can restrict snapshot construction and associate it with its originating instance.
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