Annotating static Java methods so Kotlin can pick them up as Extension functions of a type


Is it possible to add something to a Java static method so that Kotlin will recognise it as an extension function of a particular type? Having this would make the java library I’m currently writing a little nicer to use in Kotlin.


At the moment, this is not supported.


I feel like stating the obvious, but wouldn’t doing something like this work?

// Java
public static void myMethod(MyType x) { ... }

// Kotlin
fun MyType.myMethod() = myMethod(this)

I’m not 100% sure of it, but I believe you could just add a Kotlin file with your extension method definitions in your Java project, and compile everything into a jar. Usages from Java or other JVM languages wouldn’t be hindered by the kotlin-generated .class file (which they wouldn’t use).


Now you are just talking sensibly, and we will have none of that around here.


Yep, that’s the right way to do it. Just mixing in Kotlin code with your Java project also gives access to things like defining operator overloads, infix functions, inline functions etc.

In theory you could define a set of annotations for all these things in Java, but then what you’d have is a low quality annotation-based DSL that approximates the real Kotlin language. And as Kotlin is the ideal language in which to express Kotlin code, that would make little sense to me.


I suppose in @grandstaish’s case he wants to develop a java library not dependent on Kotlin runtime, but still idiomatically usable from Kotlin.


That’s exactly what I’m after. My specific case is probably quite unique as I’m writing a java annotation processor, so I actually have to dynamically generate this kotlin file. I can’t quite get it to work though, I’ve just posted the question on stackoverflow:


It would be nice to have this feature in next releases. Writing all those extension functions wrappers manually is a pain


It would make sense to make that wrapper method inline so it has zero runtime cost.


In practice, the JVM would almost always inline such a small function itself, which is why the IDE will warn you if you try putting the inline modifier there.