DEV Community

Kenji Tomita
Kenji Tomita

Posted on

2 2

Learning about @JvmMultifileClass

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.

Sentry mobile image

Tired of users complaining about slow app loading and janky UI?

Improve performance with key strategies like TTID/TTFD & app start analysis.

Read the blog post

Top comments (1)

Collapse
 
brandonirizarry profile image
BrandonIrizarry

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs