What is the equivalent of Java static methods in Kotlin?
You can achieve static functionalities found in Java using Kotlin's companion object. Declare a companion object within a class, then place your "static" methods inside of it.
The staticLike method can be called directly from MyClass in the same way we'd call upon a static method in Java.
'Static methods and Kotlin: Interplay'
Companion objects are Kotlin's way of imitating the behavior of static methods. However, it's worth noting the significance of interoperability with Java. Kotlin provides the @JvmStatic annotation to make companion object methods appear as real static methods to Java.
With the addition of @JvmStatic, Java can call MyClass.makeItJavaStatic() as if the method was defined with Java's own static keyword.
Introducing top-level and object declarations
Kotlin, in its flexible nature, offers top-level declarations. These serve for declaring global functions and properties that do not associate with a specific class. Consider them equivalent to static methods at a package level.
In case of requiring singleton behavior (akin to static initializers in Java), Kotlin's object declaration swoops in:
An important takeaway: both object and companion object allow the mixture of properties and functions. Use them separately or combine them depending on the static-like behavior you look for.
Full course meal with Kotlin: Serving static-like methods
Though Kotlin lacks a static keyword, it compensates with a broader syntax to define functions for static-like accessibility. Savor below these four serving styles:
Appetizer: Named companion objects
Name your companion object to clarify its intent and to reference it from Java:
EntrΓ©e: Factories with companion objects
Implement factory methods using companion objects. This is ideal when you want to supply a static method for object instantiation:
Side dish: Singleton with object declarations
Need a singleton β a single shared instance of a class? Kotlin's object declaration is your answer:
Dessert: Package-level utilities
Kotlin lets you declare functions at the package level. Consider them as utility functions served as dessert:
These utility functions are importable and usable as if they were static methods, without needing a holder class:
Digesting tips: Java-Kotlin Interoperability
When jumping between Kotlin and Java, remember these points for smooth operation:
- Swift integration with
@JvmStatic. - Organize companion objects with
@JvmFieldand@JvmStaticfor easy access. - Align
@file:JvmNamewith top-level declarations for a clean Java API. - Name companion objects for clear Java referencing.
In sum, Kotlin structures diverse ways for static methods, ensuring compatibility and functionality within the JVM ecosystem.
Was this article helpful?