Kotlin static methods and variables


In Java, once a method is declared as "static", it can be used in different classes without creating an object. With static methods, we don't have to create the same boilerplate code for each and every class. Here we will take an example to demonstrate how Kotlin implements static methods.

Example – Static Method in Kotlin using Companion Object

In order to implement a static method in Kotlin, we will take the help of "companion objects".

  • Companion objects are the singleton objects whose properties and functions are tied to a class but not to the instance of that class. Hence, we can access them just like a static method of the class.

  • Note that only one companion class is allowed per class. More than one companion object per class will lead to a runtime error in Kotlin.

class myClass{
   companion object{
      fun myStaticMethod(): String{
         return "This method can be called without object"
      }
   }
}
fun main(args: Array<String>) {
   println(myClass.myStaticMethod())
}

Output

On execution, it will generate the following output −

This method can be called without object

Updated on: 16-Mar-2022

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements