Kotlin prototype pattern

How to write a prototype pattern in Kotlin

An example of a prototype pattern in Kotlin.

Table of contents for design patterns in Kotlin

The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. Wikipedia

Example:

User

data class User(
    var age: Int
)

Machine

class Machine(
    var number: String
) {
    fun clone(): Machine = Machine(
        number = this.number
    )

    override fun toString(): String {
        return "Machine(number='$number')"
    }
}

Usage

fun main() {
    // for a data class
    val prototypeUser = User(
        age = 25
    )
    val userA = prototypeUser.copy()
    userA.age = 30
    println(prototypeUser)
    println(userA)

    // for not a data class
    val prototypeMachine = Machine(
        number = "UD129AG"
    )
    val machineA = prototypeMachine.clone()
    machineA.number = "JK092CD"
    println(prototypeMachine)
    println(machineA)
}

Result

User(age=25)
User(age=30)
Machine(number='UD129AG')
Machine(number='JK092CD')