- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the equivalent of Java static final fields in Kotlin?
"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
- Related Articles
- What is the equivalent of Java static methods in Kotlin?
- What is static blank final variable in Java?
- What is blank final variable? What are Static blank final variables in Java?
- Final static variables in Java
- Static and non static blank final variables in Java
- What's the Kotlin equivalent of Java's String[]?
- Initializer for final static field in Java
- Difference Between Static and Final in Java
- Kotlin equivalent of Java's equalsIgnoreCase
- Can we make static reference to non-static fields in java?
- Assigning values to static final variables in java\n
- What is the equivalent of C# namespace in Java?
- Can constructors be marked final, abstract or static in Java?
- What is final parameter in Java
- Interface variables are static and final by default in Java, Why?
