从Java使用Kotlin单例

nas*_*sch 3 java singleton android kotlin

我已经阅读了所有内容,并且看到的所有内容都表明我应该能够做到这一点,所以肯定有一些我想念的小东西。我已经将Java类转换为Kotlin:

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

我从Java调用它:

message = OrderTitle.generateMessage(activity, property);
Run Code Online (Sandbox Code Playgroud)

并得到这个错误:

error: non-static method generateMessage(Activity,Property) cannot be referenced from a static context
Run Code Online (Sandbox Code Playgroud)

kin*_*ton 6

您可以使用:

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

然后你可以从 Java 调用它:

OrderTitle.generateMessage(...)
Run Code Online (Sandbox Code Playgroud)


Ren*_*ari 5

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