Saturday, April 25, 2020

Exposing a Kotlin function only to Java code

I'm involved in a Kotlin project that's intended to be used from both Kotlin and Java code. Because Java doesn't have optional/default-value parameters, we use @JvmOverloads to generate overloads with subsequences of parameters, but we also end up writing a lot of overloads manually to remove optional parameters in the middle. These pollute Kotlin autocomplete lists, so I wanted to hide from from Kotlin code.

The @SinceKotlin annotation is meant to hide a member from sufficiently old versions of Kotlin. Specifying a bogus, extremely large version number hides the member from Kotlin in general. I defined a JAVA_ONLY string constant with a large version like 999.0, so the hiding annotation looks like @SinceKotlin(JAVA_ONLY), which is nice enough. This annotation doesn't mean anything to the Java compiler, so it's perfectly happy to use the function.

No comments:

Post a Comment