For example, I want to have a function example()
on a type Child
that extends Parent
so that I can use the function on both.
Since companion objects play by the same rules as any others, it is easy to use normal means of code reuse on them:
open class Example {
fun example() {}
}
class Parent {
companion object : Example()
}
class Child {
companion object : Example()
}
fun main(args: Array) {
Child.example()
Parent.example()
}
Alternatively with class delegation you can reuse the implementation from Parent
directly:
interface Example {
fun example()
}
class Parent {
companion object : Example {
override fun example() {}
}
}
class Child {
companion object : Example by Parent.Companion
}