3

I'm in the process of converting my codebase from Java to Kotlin, and we're converting a few classes at a time. During this process today, I noticed a really weird interop issue that I'm hoping there's a way around.

I had a package protected Java class that I converted to an internal Kotlin class. Here's an abridged version of the class:

internal class Request private constructor(internal val method: String) {

...

}

I've noticed that when I attempt to use this class from Java (within the same package), it appends the build name and a dollar sign to the end of my getter for method. Like this:

request.getMethod$myproject_debug()

If I make the method field public, this stops happening. I really hope there's a way around this, since it would be a dealbreaker in switching to Kotlin if it isn't.

user1902853
  • 399
  • 1
  • 12

1 Answers1

5

That behavior is on purpose as mentioned in the official documentation.

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;

You can tell the Jvm what method name you wish to show in Java as follows,

internal class Request constructor(@get:JvmName("getMethod") internal val method: String)

Now, you'll be able to access it from java as request.getMethod().

Chrisvin Jem
  • 3,940
  • 1
  • 8
  • 24