Skip to content

Conversation

babedev
Copy link

@babedev babedev commented Oct 16, 2019

Demonstrate how to implement Prototype pattern in Kotlin

@jolkdarr
Copy link
Contributor

jolkdarr commented Nov 30, 2019

A very simple example:

abstract class Prototype : Cloneable {
    public override fun clone() = super.clone() as Prototype
}

class ConcretePrototype1 : Prototype() {
    public override fun clone() = super.clone() as ConcretePrototype1
}

object ConcretePrototype2 : Prototype() {
    public override fun clone() = super.clone() as ConcretePrototype2
}

fun main() {
    val prototype1 = ConcretePrototype1()
    println(prototype1.clone())
    println(prototype1.clone().clone())

    println(ConcretePrototype2.clone())
    println(ConcretePrototype2.clone())
}

with the output:

ConcretePrototype1@24d46ca6
ConcretePrototype1@4517d9a3
ConcretePrototype2@372f7a8d
ConcretePrototype2@2f92e0f4

It shows two prototypes: one classic class instance and one object.
In the sample, a clone object is also a prototype.
Objects may be declared in scala or kotlin, but not yet in java.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants