What is @JvmMultifileClass?
The JvmMultifileClass annotation is described as follows.
Instructs the Kotlin compiler to generate a multifile class with top-level functions and properties declared in this file as one of its parts. Name of the corresponding multifile class is provided by the JvmName annotation.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-multifile-class/
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-name/
Let's decompile
Create a Utils.kt and define the foo method. The foo method just prints foo.
// Utils.kt
fun foo() {
println("foo")
}
When decompiled, it looks like this.
// Utils.decompiled.java
public final class UtilsKt {
public static final void foo() {
String var0 = "foo";
boolean var1 = false;
System.out.println(var0);
}
}
Let's add @JvmName and @JvmMultifileClass.
// Utils.kt
@file:JvmName("NewUtils")
@file:JvmMultifileClass
fun foo() {
println("foo")
}
Let's decompile. I specified NewUtils in the @JvmName annotation, the NewUtils class was generated. In addition, a facade class (NewUtils__UtilsKt) has been generated.
// Utils.decompiled.java
public final class NewUtils {
public static final void foo() {
NewUtils__UtilsKt.foo();
}
}
final class NewUtils__UtilsKt {
public static final void foo() {
String var0 = "foo";
boolean var1 = false;
System.out.println(var0);
}
}
If you specify @file: JvmName("NewUtils")
fot multiple files, the following error will occur.
Duplicate JVM class name 'NewUtils' generated from: package-fragment, package-fragment
This can be solved by adding @JvmMultifileClass. @JvmMultifileClass annotation can be used to generate and organize facade classes.
Top comments (1)
Interesting. I came across this in the context of how to organize extension functions in a Kotlin codebase, and had come across this SO answer. However, the answer isn't clear on how to use that annotation, which is what brought me here.