like
like

Reputation: 263

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.

Upvotes: 5

Views: 886

Answers (2)

hotkey
hotkey

Reputation: 147991

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:

Upvotes: 7

voddan
voddan

Reputation: 33789

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

Upvotes: 1

Related Questions