简体   繁体   中英

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

@JvmStatic注释函数,以便在编译时生成真正的静态Java函数。

You can use:

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

and then you can call it from Java:

OrderTitle.generateMessage(...)

The idiomatic way to do this is with top level functions,

@file:JvmName("ClassNameHere")
fun generateMessage(context: Activity, otherParameter: AType? = null): AnotherType {
    // Do some things
}

Then from java just use it as

ClassNameHere.generateMessage()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM