Using @JvmStatic in kotlin - devrath/KotlinAlchemy GitHub Wiki
Observation
- When you declare a
singleton
inkotlin
, We specify asObject
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 asClass.INSTANCE.method()
. - But there is a better way to do this by mentioning
@JvmStatic
above the function and we can access it asClass.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()
);
}
}