What is the equivalent of Java static final fields in Kotlin?

Kotlin Mobile DevelopmentApps/Applications

"static" is a Java keyword that helps developers to define a class member, whereas the keyword "final" is used to declare a constant variable in Java. Once a variable is declared as static in Java, the value of the variable remains unchanged in every instance of the object. Similarly, once a variable is declared as final, its value cannot be altered.

In this article, we will see how we can implement the same concept using Kotlin library function.

Example - using companion object

A "companion object" is an object which is declared in the same file as a class. Both the class and the companion object will have the same name and they can access each other's private data members. In the following example, we will see how we can create a companion object and use its private data members like static data members in Java.

fun main(args: Array<String>) {
   print(myClass.myStaticEqu)
}

class myClass {
   companion object {
      const val myStaticEqu = 10
   }
}

Output

It will generate the following output

10

Example - Using @JvmStatic annotation

The above scenario can be implemented using JvmStatic annotation. This will be useful while using JVM. The following example demonstrates how it works.

fun main(args: Array<String>) {
   print(myClass.myStaticEqu)
}
class myClass {
   companion object {
      @JvmStatic val myStaticEqu = 10
   }
}

Output

It will generate the following output

10
raja
Updated on 23-Nov-2021 07:01:54

Advertisements