How to convert a Kotlin source file to a Java source file?

Kotlin Mobile DevelopmentApps/Applications

Kotlin is a statistically typed language that runs on JVM. Once a Kotlin file is compiled, it creates a .class file that can be executed on the JVM. In this article, we will see how we can convert a Kotlin source file to a Java source file. In this process, we will be taking help from different online Decompilers available on the Internet.

  • Open VS Code.

  • Go to the "extension" section and install "Kotlin language support for VS Code" and "Code Runner". We need these two extensions to run Kotlin in VS code environment.

  • Install Kotlin compiler in your system as per the direction given in the Kotlin official page https://kotlinlang.org/docs/command-line.html/

  • Once your system setup is ready, you can check through your terminal whether Kotlin is properly installed or not. If installed properly, you can check their corresponding versions on the terminal.

java -version
openjdk version "14.0.2" 2020-07-14
OpenJDK Runtime Environment (build 14.0.2+12-Ubuntu-120.04)
OpenJDK 64-Bit Server VM (build 14.0.2+12-Ubuntu-120.04, mixed
mode, sharing)

Once you check for the Kotlin version, you will get the following output

kotlin -version
Kotlin version 1.5.31-release-548 (JRE 14.0.2+12-Ubuntu-120.04)

The above output implies that your local setup is ready to be used in Kotlin programming.

  • All the setup is done; now you have to create a file with ".kt" extension and run it in your VS code. For this example, we will be considering the following example file.

fun main(args: Array<String>) {
   println("Hello world !!")
}
  • Once you run the above piece of code, it will generate the following output.

Hello world !!
  • After executing successfully, it will create a jar file in the same workspace.

  • You can search for an online decompiler. For this example, we will be using https://jdec.app/./ Try to upload the jar file and you will get the corresponding Java file.

/* Decompiler 0ms, total 349ms, lines 20 */
import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;

@Metadata(
   mv = {1, 5, 1},
   k = 2,
   xi = 48,
   d1 =
   {"\u0000\u0012\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u00
   10\u0011\n\u0002\u0010\u000e\n\u0000\u001a\u0019\u0010\u0000\u
   001a\u00020\u00012\f\u0010\u0002\u001a\b\u0012\u0004\u0012\u00
   020\u00040\u0003¢\u0006\u0002\u0010\u0005"},
   d2 = {"main", "", "args", "", "", "([Ljava/lang/String;)V"}
)
public final class HelloWorldKt {
   public static final void main(@NotNull String[] args) {
      Intrinsics.checkNotNullParameter(args, "args");
      String var1 = "Hello world !!";
      boolean var2 = false;
      System.out.println(var1);
   }
}
raja
Published on 23-Nov-2021 05:41:21

Advertisements