Kotlin is a modern programming language, that does not have the same syntax Static variables, and functions as in Java. In Kotlin it follows a concept of companion objects to achieve similar functionality. In this tutorial, we will explore how to define and use static variables and functions in Kotlin using companion objects along with easy practical examples.
Understanding Static Variables and Functions in Kotlin
What are Static Variables and Functions in Kotlin?
In programming language, Static variables and functions are associated with a class rather than an instance(object) of the class. They are used to maintain their behavior across all instances of the class.
Key Difference between a Normal and a Static Function in Kotlin?
- Normal(Instance) function: A normal function always belongs to an instance of the class. It can call using objects only. Normal functions can access non-static members and properties. It requires an instance to exist and take more memory in a program.
- Static(Class) function: A Static function always belongs to the Class itself. It can be called using Class Name with Dot operator. The Static function cannot access the non-static members directly. It is faster and memory efficient than normal function because there is no need for an instance.
Defining Static Variables in Kotlin:
In Kotlin we can define Static variables using companion objects. A companion object is always tied to a class.
1 2 3 4 5 6 7 8 9 10 11 12 |
class MathUtils { companion object { const val PI = 3.14 // Static variable } } fun main() { println("Value of PI: ${MathUtils.PI}") } // Output // Value of PI: 3.14 |
Defining Static Functions in Kotlin:
We have defined 2 static functions one for returning the Square of the number and the other for printing message on screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class MathUtils { companion object { fun square(num: Int): Int { return num * num } fun printCommonMessage(){ println("Welcome Friends") } } } fun main() { val result = MathUtils.square(5) println("Square of number: $result") MathUtils.printCommonMessage() } // Output // Square of number: 25 // Welcome Friends |
Kotlin has provided a clean way to manage Static members and functions using companion objects. You can master them by practicing, Happy coding.