如何在 Java 文件中 运行 Kotlin 库(通过 JitPack 分发)?

How do I run Kotlin libraries ( distributed via JitPack ) in a Java file?

我开发了一个库 Text2Summary for Android which is written using Kotlin. I am distributing this library using JitPack 并且构建过程非常顺利。

现在,在支持 Kotlin 的 Android 项目中,我可以导入库中可用的 类。在只有 Java(未配置 Kotlin)的项目中情况并非如此。在这里,Android Studio 只是抱怨 cannot resolve symbol Text2Summary.

I have written the whole library in Kotlin and developers not using Kotlin are complaining about the same cannot resolve symbol Text2Summary error. Should I simply convert the Kotlin code back to Java code or should I tell the users to enable Kotlin by apply plugin 'kotlin'? A valid explanation will be helpful too.

我认为您忘记添加 @JvmStatic 注释以使您的方法可从 Java 代码调用。没有它,你必须像 MyObject.Companion.method1() in Java.

那样调用它

这是您应该添加到 companion object {}

中的 public 方法中的内容

class Text2Summary() {

    companion object {

        // Summarizes the given text.
        @JvmStatic
        fun summarize( text : String , compressionRate : Float ): String {
            val sentences = Tokenizer.paragraphToSentence( Tokenizer.removeLineBreaks( text ) )
            val tfidfSummarizer = TFIDFSummarizer()
            val p1 = tfidfSummarizer.compute( text , compressionRate )
            return buildString( sentences , p1 )
        }

        // Summarizes the given text. Note, this method should be used whe you're dealing with long texts.
        // It performs the summarization on the background thread. Once the process is complete the summary is
        // passed to the SummaryCallback.onSummaryProduced callback.
        @JvmStatic
        fun summarizeAsync( text : String , compressionRate : Float , callback : SummaryCallback ) {
            SummaryTask( text , compressionRate , callback ).execute()
        }
    }
}