October 2018
Intermediate to advanced
370 pages
9h 15m
English
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() ...
Read now
Unlock full access