Explain Codes LogoExplain Codes Logo

What is the equivalent of Java static methods in Kotlin?

java
kotlin-static-methods
java-interoperability
kotlin-features
Anton ShumikhinbyAnton ShumikhinΒ·Sep 14, 2024
⚑TLDR

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.

class MyClass { companion object { fun staticLike() = "It works like a static method! πŸš€" } } val staticCall = MyClass.staticLike()

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.

class MyClass { companion object { @JvmStatic fun makeItJavaStatic() = "Java thinks I'm static now! 🎩" } }

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.

// Top level of a Kotlin file fun universalFunction() = "I'm static on a higher plane! 🌠" // Can access universally, requiring an import in other packages val result = universalFunction()

In case of requiring singleton behavior (akin to static initializers in Java), Kotlin's object declaration swoops in:

object Singleton { init { // Initialize something once for the application life-cycle (no extra lives here! πŸ™…β€β™€οΈ) } fun doSomething() = "Do it once, do it right! πŸ’ͺ" }

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:

class Toolkit { companion object Factory { fun create() = Toolkit() } } // Java access: Toolkit.Factory.create(); // Now it makes sense why it's 'Factory', right?

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:

class DatabaseDriver { companion object { fun connect(url: String) = DatabaseDriver() // Knocks on the database door and enters! πŸšͺ } }

Side dish: Singleton with object declarations

Need a singleton – a single shared instance of a class? Kotlin's object declaration is your answer:

object Repository { fun getData() = "I've got all the data you need! πŸ“š" }

Dessert: Package-level utilities

Kotlin lets you declare functions at the package level. Consider them as utility functions served as dessert:

package utils fun log(m: String) = "Logging... but without trees! 🌳"

These utility functions are importable and usable as if they were static methods, without needing a holder class:

import utils.log fun main() { log("Logging from Main. The view is great up here! πŸŒ„") }

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 @JvmField and @JvmStatic for easy access.
  • Align @file:JvmName with 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.