Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Kotlin singleton from Java

I've read up on this and everything I'm seeing says I should be able to do this so there must be some little thing I'm missing. I've converted a Java class to Kotlin:

object OrderTitle {
  @JvmOverloads
    fun generateMessage(context: Activity, otherParameter: AType? = null): AnotherType {
        // Do some things
   }
}

And I call it from Java:

message = OrderTitle.generateMessage(activity, property);

and get this error:

error: non-static method generateMessage(Activity,Property) cannot be referenced from a static context
like image 514
nasch Avatar asked Apr 22 '19 15:04

nasch


People also ask

Can Java and Kotlin be used together?

If your question is can you use kotlin files in java files and vice versa then the answer is yes.

Can I use a Kotlin library in Java?

Android Studio provides full support for Kotlin, enabling you to add Kotlin files to your existing project and convert Java language code to Kotlin. You can then use all of Android Studio's existing tools with your Kotlin code, including autocomplete, lint checking, refactoring, debugging, and more.

Is singleton thread-safe Kotlin?

Conventional Singleton@Volatile and synchronized() are used to make sure this Singleton creation is thread-safe.


1 Answers

Annotate your function with @JvmStatic so a real static java function is generated when compiling.

like image 53
Rene Ferrari Avatar answered Sep 19 '22 10:09

Rene Ferrari