Skip to content

Using @JvmStatic in kotlin

Devrath edited this page Oct 12, 2023 · 2 revisions

Observation

  • When you declare a singleton in kotlin, We specify as Object class, and since the singleton is simple.
  • Now say you need to access the singleton function from a java class as below, You need to use it as Class.INSTANCE.method().
  • But there is a better way to do this by mentioning @JvmStatic above the function and we can access it as Class.method().

Code

KotlinUtils.kt

object KotlinUtils {
    fun getActorName(): String{ return "John" }
    @JvmStatic
    fun getActressName(): String{ return "Sarah" }
}

DemoJvmStaticAnnotation.java

public class DemoJvmStaticAnnotation {
    public void initiate() {
        // Actor name cannot be accessed without using INSTANCE
        System.out.println(
                KotlinUtils.INSTANCE.getActorName()
        );
        // Observe that here the INSTANCE is not used because @JvmStatic is mentioned
        System.out.println(
                KotlinUtils.getActressName()
        );
    }
}
Clone this wiki locally