Kotlin memento pattern

How to write a memento pattern in Kotlin

An example of a memento pattern in Kotlin.

Table of contents for design patterns in Kotlin

The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback). Wikipedia

Example:

Memento

data class Memento(
    val letter: String,
    val time: LocalDateTime
)

Editor

class Editor(var letter: String) {

    fun createMemento(): Memento = Memento(letter, LocalDateTime.now())

    fun restore(memento: Memento) {
        letter = memento.letter
        println("Restored to: ${memento.time}")
    }
}

History

class History(private val editor: Editor) {
    private val mementoList = ArrayList<Memento>()

    fun saveState() = mementoList.add(editor.createMemento())

    fun restore(index: Int) = editor.restore(mementoList[index])
}

Usage:

fun main() {
    val editor = Editor("")
    val history = History(editor)

    editor.letter = "Draft #1"
    history.saveState()
    println(editor.letter)

    editor.letter = "Draft #2"
    editor.letter = "Draft #3"
    history.saveState()
    println(editor.letter)

    history.restore(0)
    println(editor.letter)

    history.restore(1)
    println(editor.letter)
}

Result

Draft #1
Draft #3
Restored to: 2020-08-09T17:17:29.045170
Draft #1
Restored to: 2020-08-09T17:17:29.045579
Draft #3