We can also call the Kotlin singleton class in Java. Let's create a singleton class in Kotlin by using the object keyword:
object Singleton {
fun happy() {
println("I am Happy")
}
}
Furthermore, we can call the Singleton class and the happy function in Java by using the INSTANCE keyword:
public static void main(String args[]) {
Singleton.INSTANCE.happy();
}
Notice that we do not need to use a Kotlin filename as a reference, but the object class name, Singleton, is sufficient. We can skip the INSTANCE keyword as well. Add the @JvmStatic annotation at the beginning of the function signature:
object Singleton {
fun happy() {
println("I am Happy")
}
@JvmStatic fun excited() {
println("I am very Excited")
}
}
Once this is done, call the excited function directly without using the INSTANCE keyword in Java:
public static void main(String args[]) {
Singleton.INSTANCE.happy();
Singleton.excited();
}
Execute the Java program and verify the output, as follows:
I am Happy
I am very Excited