5

How to access an internal Kotlin method through Java class without using the wierd syntax < method_name >$< module >()?

Code example.

Kotlin class:

class MyKotlinClass {
    internal fun myInternalKotlinMethod() {
        // Do something
    }
}

Java class:

public class MyJavaClass {
    public MyJavaClass() {
        MyKotlinClass myKotlinClass = new MyKotlinClass();
        myKotlinClass.myInternalKotlinMethod$app_debug();
    }
}
2
  • Is MyJavaClass & MyKotlinClass part of different modules right? Commented Oct 2, 2019 at 12:27
  • They are at same module Commented Oct 2, 2019 at 12:35

3 Answers 3

7

There is no way around this. This is how it is supposed to work.

According to the official docs on calling Kotlin code from Java code (emphasis mine):

  • internal declarations become public in Java. Members of internal classes go through name mangling, to make it harder to accidentally use them from Java and to allow overloading for members with the same signature that don't see each other according to Kotlin rules;
Sign up to request clarification or add additional context in comments.

Comments

5

You may use JvmName to achieve the point:

class MyKotlinClass {
    @JvmName("myInternalKotlinMethod")
    internal fun myInternalKotlinMethod() {
        // Do something
    }
}

Comments

3

AFAIK there isn't any other alternative to call internal from Java Class. If you can decompile your Kotlin code to Java; you will exactly see how Kt is converted to Java. So to invoke that method must be using the same naming convention.

If you are using IntelliJ, you can use Tools → Kotlin → Show kotlin ByteCode → Decompile

Decompiled Kotlin to Java Class

MyKotlinClass.kt → MyKotlinClass.java(Decompiled)

public final class MyKotlinClass {
  //app_debug is your module name
  public final void myInternalKotlinMethod$app_debug() {

  }
}

MyJavaClass.java

public class MyJavaClass {
   public MyJavaClass() {
     MyKotlinClass myKotlinClass = new MyKotlinClass();
     myKotlinClass.myInternalKotlinMethod$app_debug();
  }
} 

I'm afraid you have to use myInternalKotlinMethod$app_debug(); from java class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.