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.
import kotlin.reflect.KProperty
// Base class
open class Base(val num: Int) {
fun describe(): String = "base with num=$num"
}
// Container class that delegates to Base
class Container(base: Base, val str: String) : Base by base {
// Additional property
// str is already declared in the primary constructor
}
// Interface for describing
interface Describer {
fun describe(): String
}
fun main() {
// Creating an instance of Container
val co = Container(Base(1), "some name")
// We can access the base's properties directly on co
println("co={num: ${co.num}, str: ${co.str}}")
// We can also access the describe method from Base
println("describe: ${co.describe()}")
// Container implements Describer interface through delegation
val d: Describer = co
println("describer: ${d.describe()}")
}To run the program, save it as ClassDelegation.kt and use the Kotlin compiler:
$ kotlinc ClassDelegation.kt -include-runtime -d ClassDelegation.jar
$ java -jar ClassDelegation.jar
co={num: 1, str: some name}
describe: base with num=1
describer: base with num=1In this Kotlin example:
We define a
Baseclass with anumproperty and adescribe()method.Instead of embedding, we use class delegation in the
Containerclass. TheBase by basesyntax in the class declaration allowsContainerto inherit all members fromBase.We create an instance of
Containerin themainfunction, passing aBaseinstance and a string.We can access the
numproperty anddescribe()method directly on theContainerinstance, as if they were defined inContainer.We define a
Describerinterface thatBaseimplicitly implements. Due to delegation,Containeralso implements this interface.We demonstrate that
Containercan be used where aDescriberis 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.