Struct Embedding in Kotlin
Kotlin supports composition of types through delegation and inheritance. This example demonstrates how to use class delegation to achieve a similar effect to Go’s struct embedding.
To run the program, save it as ClassDelegation.kt
and use the Kotlin compiler:
In this Kotlin example:
We define a
Base
class with anum
property and adescribe()
method.Instead of embedding, we use class delegation in the
Container
class. TheBase by base
syntax in the class declaration allowsContainer
to inherit all members fromBase
.We create an instance of
Container
in themain
function, passing aBase
instance and a string.We can access the
num
property anddescribe()
method directly on theContainer
instance, as if they were defined inContainer
.We define a
Describer
interface thatBase
implicitly implements. Due to delegation,Container
also implements this interface.We demonstrate that
Container
can be used where aDescriber
is expected.
This approach in Kotlin achieves a similar effect to Go’s struct embedding, allowing for a form of composition that provides access to the members of the delegated class.