Kotline Static example

High level languages has static keyword applied to class members and static variables created single per class and shared among object of the class. Static methods called with class names only.

Kotlin language does not defined static functions and variables for a class

There is no static defined in Kotline language.

Let’s define static members and variables in Kotilin

Kotlin Static functions and variables examples

There are multiple ways we can create a Static functionality in Kotlin.

  • using companion object. Companion object declared inside a class that contains constants and functions, treaded as static. You can access these only inside a class.

For example, Let’s define a static method in java

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

Static methods called using Classname in java. For example Employee.getName();

The same above an defined in Kotlin using companion object.

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

Static members can be called as given below

Inside Same class, called using class. Example Employee.getName()

Static variables: You can also declare static constants in side a companion object

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

Companion object notes:

  • Companion object access all members (public,private functions and variables)of an class inside only.

  • Companion object initialized its members when class is initialized

  • Members of the Companion called using Class name.

  • Second way using object class Object class can be declared with static functions and variables.

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

Static Variable constatns declares using object class

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