Simple sample for the template method pattern in Kotlin.

package org.devll.samples.kotlin.designpattern

sealed class Drink {
    fun prepareDrink() {
        println("prepare ${this.javaClass.simpleName} ...")

        boilWater()
        addIngredient()
        fillWaterInCup()

        println("... finished\n")
    }

    /** template method */
    protected abstract fun addIngredient()

    private fun boilWater() = println("boil water")
    private fun fillWaterInCup() = println("fill cup with hot water")
}

object Coffee : Drink() {
    override fun addIngredient() = println("insert coffee powder")
}

object Tea : Drink() {
    override fun addIngredient() = println("insert tea leaves")
}


fun main() {
    Coffee.prepareDrink()
    Tea.prepareDrink()
}
Console output
prepare Coffee ...
boil water
insert coffee powder
fill cup with hot water
... finished

prepare Tea ...
boil water
insert tea leaves
fill cup with hot water
... finished
Implementation notes
  • Non-open Kotlin methods are final by default

  • object is used instead of class as the class has no state

  • sealed is optional and can only be used if all subclasses are known in advance

'; ?>