Companion objects

Other programming languages, including Java and C#, allow us to use static variables and static functions. We can declare functions as static when they are utility functions that should be accessible without having to create a class object. Kotlin, however, does not provide a static keyword for a variable or a function. Instead, it allows us to add a companion object inside the class to declare a static function or variable.

Let's take a look at how to declare a companion object.

Create a normal class called Parent. Within the class body, declare a companion object:

class Parent {

companion object {

const val count = 10
fun companionFunction() {
println("I am your companion")
}
}

fun getCompanions(){
companionFunction()
}

fun memberFunction(){
println("I am your member function")
}
}

Each function and variable declared within the companion object will behave as static. The companion object informs its main class that it is the main class' companion and that the main class can directly access all the member functions and variables.

Parent is a normal class that can access its own functions by creating a class instance. To access the members of the companion object, however, we don't need to create an instance of the Parent class. The members of the companion object are accessible directly by using the class name as a reference:

fun main(args: Array<String>) {
Parent.companionFunction()
println(Parent.count)

val obj = Parent()
obj.memberFunction()
obj.getCompanions()
}

CompanionFunction will print the message and Parent.count will display the value in the count variable. The most important point is the getCompanions function, which can call the function from companion object:

As we can see, obj is an instance of the Parent class that can call memberFunction(). All members of the companion objects are directly accessible using the name of the Parent class. We do not need to use the class name as a reference if we are calling the companion class function from inside our class body. The getCompanions() function within the Parent class body calls companionFunction() without using the class name.

We can also assign a name to the companion object. This doesn't make any difference, apart from improving the readability of the code. However, just because Kotlin allows us to assign a name to the companion object doesn't mean that we can declare another companion object in the same class with a different name. Kotlin only allows one companion object per class:

class Parent {
companion object Static {
const val count = 10
fun companionFunction() {
println("I am your companion")
}
}
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.52.188