Open In App

How to Convert a Kotlin Source File to a Java Source File in Android?

Improve
Improve
Like Article
Like
Save
Share
Report

We use Android Studio to translate our Java code into Kotlin while transitioning from Java to Kotlin. But what if we need to convert a Kotlin file to its Java equivalent? We’ll examine how to convert a Kotlin source file to a Java source file in this blog. Let’s get this party started. Because of its interoperability with Java, Kotlin grew at an exponential rate when it first appeared. This is because the Java Virtual Machine executes both Java and Kotlin (JVM).

Image #1: Understanding the conversion structure.

Compiling Kotlin code to JVM bytecode and subsequently decompiling the bytecode to Java code are the two processes involved in converting a Kotlin file to a Java file. As a result, converting Java code to Kotlin and vice versa is simple. Some of the benefits or motivations for translating Kotlin code to Java code are as follows:

  1. To incorporate functionality that is simple to build in Java.
  2. To look into a performance issue.
  3. To remove Kotlin from your project, follow these steps.

To convert the file, as mentioned, follow the below-written steps

Open your Kotlin project in your preferred IDE, here we are using IntelliJ

  1. Then go to Kotlin > Show Kotlin Bytecode in Tools > Kotlin.
  2. Your Kotlin file’s bytecode will be returned to you.
  3. To extract your Java code from the bytecode, click the Decompile button.

The Fernflower is used by IntelliJ IDEA behind the scenes. 

So, instead of utilizing IntelliJ IDEA, we may use Fernflower directly. The only demerit of using this method is that you will be getting the fern flower file which you will have to convert later on to pure java class. 

  1. Do the compile process by using the command: kotlinc filename.kt
  2. Now we must decompile the class file created in the previous step.
  3. The fernflower.jar file can be downloaded here.
  4. After you’ve downloaded the jar file, use the command following to extract the Java file from your .class file:
java -jar fernflower.jar filename.class

Although the above procedure will generate a Java file, the code will be difficult to comprehend. In addition, reading will be poor. As a result, using IntelliJ IDEA to convert Kotlin code to Java code is suggested.


Last Updated : 17 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads