Search code examples
javakotlinextension-methods

Adding Kotlin extension methods to a pure Java library


I am developing a pure Java library and want to add some Kotlin specific extension methods. Is there a way to add these extension methods to the already existing pure Java JAR or am I forced to create a new Kotlin specific module that has to be published separately? If so, will they be visible to Java users, in what way?

I don't mind using the Kotlin compiler to compile my library if this avoids the release of separate JARs just for literally 3 lines of code.

I need these extension methods to work around type-inference / method reference resolution differences between Java and Kotlin.


Solution

  • Extension methods are compiled to static Java methods, for example from app.kt into the class AppKt, i.e. they are available to Java as well using AppKt.method(), as explained in the documentation.

    Both your Java code and Kotlin code compile to Java Bytecode class files and can go into the same jar, i.e., no need to ship multiple jars. My personal build system of choice for building Kotlin/Java code is Gradle, but this is up to you.