Understanding Static Variables and Functions in Kotlin

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

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?

  1. 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.
  2. 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.

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.

Kotlin has provided a clean way to manage Static members and functions using companion objects. You can master them by practicing, Happy coding.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *