-
Notifications
You must be signed in to change notification settings - Fork 22
Using @JvmStatic in kotlin
Devrath edited this page Oct 12, 2023
·
2 revisions
- 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()
.
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()
);
}
}