Kotlin
Java
static final
programming
comparison

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Java and Kotlin are both robust programming languages utilized for developing a broad range of applications. Java has been a stalwart for developers, but Kotlin, now a first-class citizen in the Android ecosystem, has risen for its concise syntax and modern features. Among the most common constructs in Java is the static final field, often used to define constants. Here's an exploration of how Kotlin manages to provide similar functionality.

Static Finals in Java

In Java, static final is commonly used to create constants. A static field belongs to the class itself rather than an instance of the class, while a final field denotes immutability. Combining these keywords, a static final field ensures there’s exactly one constant value per class:

java
public class Example {
    public static final int STATIC_FINAL_VARIABLE = 42;
}

This ensures that STATIC_FINAL_VARIABLE is accessible without an instance of the class, and its value is immutable once initialized.

Equivalent in Kotlin

Kotlin does not directly have static fields since it embraces a more object-oriented approach. However, Kotlin supports object singletons and top-level declarations to achieve similar functionality.

Using companion object

Kotlin uses companion objects to mimic Java's static fields. The fields defined inside a companion object are tied to the class and can be accessed similarly to Java’s static members. You can also use const to achieve immutability, akin to Java's final.

kotlin
1class Example {
2    companion object {
3        const val STATIC_FINAL_VARIABLE: Int = 42
4    }
5}

Here, STATIC_FINAL_VARIABLE in Kotlin is the direct equivalent of Java's public static final int STATIC_FINAL_VARIABLE = 42;. It’s immutable and accessible without an instance of Example.

Using Top-Level Constants

A cleaner, often more idiomatic way in Kotlin is to declare constants at the top level. Kotlin allows for top-level declarations, so the constant can be placed directly in a file, outside of any class:

kotlin
const val TOP_LEVEL_STATIC_FINAL_VARIABLE: Int = 42

This top-level variable can be accessed from any other part of the code without requiring an enclosing class or singleton.

Key Differences

While companion object is one method to achieve similar functionality to static methods and fields in Kotlin, there are key differences and recommendations depending on use cases:

FeatureJava: Static FinalKotlin: Companion ObjectKotlin: Top-Level
Declaration ScopeWithin the classWithin companion objectTop level in a file
AccessClassName.FIELDClassName.FIELDDirectly by name
Need for Enclosing ClassYesTypically, for organizationNo
InitializationAt compile-time if static finalCompile-time with constCompile-time with const

Additional Tips

  • Companion Object Initialization: Keep in mind that a companion object is initialized lazily the first time it is accessed. This is unlike Java’s static initializers, which are executed during class loading.
  • Performance Considerations: Since Kotlin's companion object is technically just a singleton object, there might be performance nuances in Android environments. Top-level declarations might be faster for primitives, as they don’t require the overhead of creating a singleton object on initialization.
  • Use const Wisely: The const modifier should be used only on primitives or String types suitable for compile-time constants in Kotlin. For other types, consider using val within a companion object.

Conclusion

Kotlin's approach caters to modern programming paradigms, emphasizing conciseness and safety. The way it handles static-like constructs mirrors its philosophy of eliminating as many pitfalls and boilerplate as possible. While translating all concepts may not always be straightforward, Kotlin provides robust alternatives that often encourage better practices.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.