Kotline Static example

High-level languages have the static keyword applied to class members, and static variables are created once per class, shared among objects of the class. Static methods are called using only the class name.

However, Kotlin does not define static functions and variables in the same way.

Let’s explore how to define static members and variables in Kotlin.

Kotlin Static Functions and Variables Examples

There are multiple ways to create static functionality in Kotlin.

  • Using companion object

The companion object is declared inside a class and contains constants and functions, which are treated as static. These can be accessed only inside the class.

For example, let’s define a static method in Java:

class Employee {
  public static String getName() { return "admin"; }
}

In Java, static methods are called using the class name, like Employee.getName().

The equivalent in Kotlin using a companion object:

class Employee {
  companion object {
     fun getName() : String = "admin"
  }
}

Static members can be called within the same class using the class, for example, Employee.getName().

Static variables: You can declare static constants inside a companion object:

class Employee{
companion object {
    fun getName() = println(name)
    val name ="bar"
    }
}

Companion object notes:

  • Companion objects can access all members (public and private functions and variables) of a class only.

  • A companion object initializes its members when the class is initialized.

  • Members of the companion object are called using the class name.

  • Another way using the object class The object class can be declared with static functions and variables.

  object Util{
  fun getName(name: String ): String{
    return name;
  }
}

Static constant variables are declared using the object class.

object Const {
    const val DEFAULT = "test"
    const val AGE = 25
}