To demonstrate the renaming of a generated class, we'll make use of the @JvmName annotation within our GreetingFunctions.kt file. Here, we've added the @JvmName annotation to our GreetingFunctions.kt file using the @file use-site target (we'll talk more about use-site targets later on in this chapter):
@file:JvmName("GreetingsHelper")
// GreetingFunctions.kt
fun sayHello(name: String) = println("Hello $name!")
Within the @JvmName annotation, we've specified the "GreetingsHelper" stringĀ as the name we'd like to use for the compiler-generated class. After this addition, calling the sayHello() function from Kotlin is unchanged:
// Main.kt
fun main() {
sayHello("Nate")
}
But now, when calling the sayHello() function from Java, we have a different enclosing class to reference; GreetingsHelper:
// Main.java
public class Main {
public static void main(String[] args) {
GreetingsHelper.sayHello("Nate");
}
}
Now, the generated class directly matches the name that's passed to the @JvmName annotation. Changing this name allows us to hide any indication of Kotlin from the name of the class. By removing the Kt suffix from the class name, it's no longer obvious to the caller that the class or method is written in Kotlin. This improves the interop experience by hiding that implementation detail.
This process of generated class naming not only works for top-level functions, but for top-level properties as well, as we will examine in the next section.