Search code examples
javakotlinsyntaxidiomslanguage-interoperability

How can one access Kotlin's `backtickedFunctions` from Java?


TL;DR:

Is there a simple syntax in java to access kotlins backticked functions such as fun `if`(){...}

Long Version:

In Kotlin, one may write the following class.

class ShapeShifter {
    fun speak() { println("Hello fellow hooman") }
    fun `speakLikeA🐱`() { println("Meow") }
    fun `speakLikeA🐶`() { println("Bwoof !") }
    fun `speakLikeA🐧`() { println("NOOT NOOT ! (you would'nt have so much problems with linux ...)") }
}

And this would work just fine ... All your fellow kotlin-ers would be able to speak to you in all your forms like so :

ShapeShifter().`speakLikeA🐶`() // would work like a charm

but when interracting with java-ist muggles your secret identity would be safe because I am pretty sure java-ists can only interract with you like so :

new ShapeShifter().speak()

My question is : Is there a way for java commoners to reach to your backticked kotlin functions WITHOUT resorting to using black magics such as introspection/reflection like so :

var tomJedusor = new ShapeShifter();
ShapeShifter.class.getDeclaredMethod("speakLikeA🐍").invoke(tomJedusor); //the forbidden arcane spell banned from Konoha ...

Solution

  • @JvmName annotation lets you define jvm name for that method.

    @JvmName("speakLikeACat")
    fun `speakLikeA🐱`() { println("Meow") }
    
    @JvmName("speakLikeADog")
    fun `speak like a 🐶`() { println("Bwoof") }
    

    Now, you can access that method from java code.

    // .java 
    shapeShifter.speakLikeACat();
    shapeShifter.speakLikeADog();
    

    Accesing backticked kotlin methods, fields from java is only possible with some jvm annotations. Kotlin compiler must obey java language specifications to generate the byte code. Actually java language specification does not allow this feature.