DEV Community

loading...

Learning about @JvmMultifileClass

tommykw profile image Kenji Tomita ・1 min read

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")
}
Enter fullscreen mode Exit fullscreen mode

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);
   }
}
Enter fullscreen mode Exit fullscreen mode

Let's add @JvmName and @JvmMultifileClass.

// Utils.kt

@file:JvmName("NewUtils")
@file:JvmMultifileClass

fun foo() {
    println("foo")
}
Enter fullscreen mode Exit fullscreen mode

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);
   }
}
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (0)

pic
Editor guide