Home > Software engineering >  How to use Kotlin Singleton class in Java
How to use Kotlin Singleton class in Java

Time:08-24

I've both Kotlin and Java files in my project. I converted a Java Singleton class in Kotlin using object MySingletonClass. But still this is being used by many java classes so added the fun like this to use in Java

 @JvmStatic
    fun getInstance(): MySingletonClass{
       return this@MySingletonClass
    }

but when I compile the project get below error in all Java files Cannot access class 'MySingletonClass'. Check your module classpath for missing or conflicting dependencies

The main question is how I could use Kotlin Object in Java.

CodePudding user response:

You don't need to write any special function to use a Kotlin singleton object in Java. You can use the INSTANCE field, which the Kotlin compiler creates for you:

// In Java:
MySingletonClass obj = MySingletonClass.INSTANCE;

However, you said in your question that Java throws an error saying it cannot access the class MySingletonClass. That's a separate issue. Check that you're using the right package name in your import statement.

  • Related