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

Tags: , , ,



I have developed a library Text2Summary for Android which is written using Kotlin. I am distributing this library using JitPack and the building process goes perfectly fine.

Now, in a Kotlin-enabled Android project, I am able to import the classes available in the library. This is not the case in a project which only has Java ( no Kotlin configured ). Here, Android Studio simply complains that 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.

Answer

I think you forgot to add @JvmStatic annotation to make your method callable from Java code. Without it, you have to call it like MyObject.Companion.method1() in Java.

Here is what you should add to your public methods in companion object {}

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()
        }
    }
}


Source: stackoverflow