How to convert a Kotlin source file to a Java source file?
While migrating from Java to Kotlin, we convert our Java code into Kotlin with the help of Android Studio. But what if we want to convert a Kotlin file to it’s equivalent Java file? So, in this blog, we will see how to convert a Kotlin source file to a Java source file. Let’s get started.
When Kotlin came into existence, it started growing exponentially because of its interoperability with Java. This is because both Java and Kotlin runs on Java Virtual Machine (JVM).
Converting a Kotlin file to Java file involves two steps i.e. compiling the Kotlin code to the JVM bytecode and then decompile the bytecode to the Java code. So, it becomes easy to convert the Java code into Kotlin and vice-versa.
Following are some of the advantages or reasons for converting Kotlin code to Java code:
- To integrate some feature that can be easily implemented in Java.
- To investigate some performance issue.
- To remove Kotlin from your project.
Steps to convert your Kotlin source file to Java source file:
- Open your Kotlin project in the IntelliJ IDEA / Android Studio.
- Then navigate to Tools > Kotlin > Show Kotlin Bytecode.
- You will get the bytecode of your Kotin file.
- Now click on the Decompile button to get your Java code from the bytecode.
Under the hood, the IntelliJ IDEA uses the Fernflower. So, instead of using the IntelliJ IDEA, we can directly use Fernflower. But the demerit of this method is that you will not get the pure Java file and you need to manually download the Fernflower jar file. To use Fernflower, follow the below steps:
- Compile your Kotlin code by: kotlinc filename.kt
- Now, we need to decompile the class file generated after the first step. Download the fernflower.jar file.
- After downloading the jar file, run the below command to get the Java file, out of your .class file:
java -jar fernflower.jar filename.class
The above method will generate the Java file but the code will be complicated to understand. Also, readability will be very poor. So, it is recommended to convert the Kotlin code to Java code with the help of IntelliJ IDEA.
Hope you learned something new today.
Do share this blog with your fellow developers to spread the knowledge. You can read more blogs on Android on our blogging website .
Apply Now: MindOrks Android Online Course and Learn Advanced Android
Happy Learning :)
Team MindOrks!