0

Kotlin Class Delegation Example


Udemy

This post shows how to implement the Delegation Design Pattern in Kotlin.

We are using Kotlin 1.1.

From Java

For some idea on how to use the design pattern and it the benefits it brings, please see:

Inheritance and Delegation Design Pattern Examples in Java

To and in Kotlin

In Kotlin, it has what it calls Class Delegation facility that enables programmers to quickly implement the Delegation Pattern with the by-clause.

The codes below use this delegation facility but all methods of supposedly subclasses are overridden. At the very bottom, after the initial test, we’ll modify an existing “derived” class and test the codes again.

Canine.kt (Interface)

This interface ensures all classes (and supposedly “subclasses”) conform to specific set of behaviors.

Dog.kt (Class / generic dog)

This class represents any dog (dog=canine). The term dog is a very broad classification.

Our generic dog barks “generically” and is labeled as “Generic Canine”.

Pitbull.kt

A Pitbull represents a specific kind of dog. It barks differently from the generic dog.

Pluto.kt

Pluto is another dog. It is a specific dog very different from our generic dog.

Testing

This is our main function. Consider first the Pitbull object. During instantiation, an object of Dog class (generic dog) is passed to the contructor.

The Pitbull may use the characteristics of a generic dog using a Dog object. However, a Pitbull is a specific kind of a dog. Those generic characteristics are “replaced” with the Pitbull’s characteristics.

This outputs:

For Pluto, we passed in a Pitbull object. This means that Pluto has “evolved” from a Pitbull but has its own style of barking and whatnot.

By-clause and test again

Take note of the previously generated output. Now, we modify the Pluto class a bit.

Our codes now output:

Pluto now barks like a Pitbull.

References

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert