How to make some method be visible only to kotlin

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

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

+5
source share
2 answers

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

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

The marked item can still be used in Kotlin in normal mode.

Unfortunately, @JvmSynthetic cannot be used to indicate a class (it does not have a CLASS target).

More details:

+6
source

Some methods in Kotlin stdlib are marked with inline annotation @kotlin.internal.InlineOnly . This forces the compiler to embed them in kotlin code without generating the appropriate methods in the JVM classes.

This trick is used to reduce the number of methods on stdlib. This is a dangerous solution and may cause problems with separate compilation if used improperly.

Catch: annotation @kotlin.internal.InlineOnly is internal and can only be used in the standard library. I do not know what plans to release in the public API.

TL DR: you can do it, but only if you contribute to Kotlin stdlib

+1
source

Source: https://habr.com/ru/post/1270410/


All Articles