Welcome to this comprehensive guide on Kotlin Companion Object Extensions! This lesson is designed for both beginners and intermediates, so let's dive right in.
Companion objects in Kotlin are static objects that are associated with a class but are not created as an instance of the class. They are useful when you need to share utility functions or data between instances of the class.
class MyClass {
companion object {
val SHARED_DATA = "Shared Data"
fun sharedFunction() {
println("Shared Function")
}
}
}In the above example, MyClass has a companion object with a shared data and a shared function.
Starting from Kotlin 1.3, you can extend companion objects, just like you extend classes. This allows you to reuse and build upon existing companion objects.
class MyClass {
companion object Base {
val BASE_DATA = "Base Data"
fun baseFunction() {
println("Base Function")
}
}
}
class MyClassExtended : MyClass() {
companion object Extended : MyClass.Base() {
val EXTENDED_DATA = "Extended Data"
fun extendedFunction() {
println("Extended Function")
}
}
}In the above example, MyClass has a companion object Base. MyClassExtended extends MyClass and also extends the Base companion object, creating a new companion object Extended.
Now, let's see how to use the extended companion object:
fun main() {
val myClass = MyClassExtended()
println(MyClassExtended.Extended.EXTENDED_DATA) // Prints: Extended Data
MyClassExtended.Extended.extendedFunction() // Prints: Extended Function
println(MyClass.Base.BASE_DATA) // Prints: Base Data
MyClass.Base.baseFunction() // Prints: Base Function
}In the main function, we create an instance of MyClassExtended, and then access both the original Base companion object and the extended Extended companion object.
What is the purpose of extending a companion object in Kotlin?