How to force some method to be visible only to kotlin

I want some method to be visible only to kotlin code and not to Java code.

For example, here is a method fun method(){} that can only be called in kotlin code and cannot be called in Java code.

You can achieve exactly what you want by using the @JvmSynthetic annotation. It marks the element with the synthetic flag in the JVM bytecode, and its usage becomes an error in Java sources (not quite sure about other JVM languages, needs checking, but likely it will work as well):

@JvmSynthetic
fun f() { /*...*/ }

The marked element can still be used in Kotlin normally.

Unfortunately, @JvmSynthetic cannot be used to mark a class (it has no CLASS target).

See more:

  • What’s the intended use of @JvmSynthetic in Kotlin? (no answer there, but the effect is described in the question)

  • Inline function cannot access non-public-API: @PublishedApi vs @Suppress vs @JvmSynthetic, about how it can be used to hide effectively public internal members.

Some methods in Kotlin stdlib are marked inline with the @kotlin.internal.InlineOnly annotation. That makes the compiler to inline them into the kotlin code without generating corresponding methods in JVM classes.

This trick is used for reducing method count on stdlib. This is a dangerous solution and can cause problems with separate compilation when used incorrectly.

The catch: the @kotlin.internal.InlineOnly annotation is internal and can be used only in the standard library. I know of no plans of releasing it into the public API.

TL;DR: You can do it, but only if you are contributing to Kotlin stdlib