How to Convert Kotlin Code to Java Code in Android Studio?
Java programming language is the oldest and most preferred language for Android app development. However, during Google I/O 2017, Kotlin has been declared as an official language for Android development by the Google Android Team. Kotlin has gained popularity among developers very quickly because of its similarities as well as interoperable with the Java language. One can mix code of Java and Kotlin while designing an Android project. The syntax of Java and Kotlin differs in many aspects but their compilation process is almost the same. Code of both the languages gets compiled into bytecode that is executable on Java Virtual Machine(JVM). Thus if one can derive the bytecode of compiled Kotlin file, it can be decompiled in order to produce the equivalent Java code. Android Studio does exactly the same to carry out the code conversion from Kotlin to Java. Developers may have many reasons to convert the Kotlin code into Java such as:
- To integrate features that are easy to implement in Java language.
- To resolve some performance issue that is difficult to locate in Kotlin.
- To remove the Kotlin code from the project files.
Step 1: Open Kotlin Class/File
Open the Kotlin Class/File which is to be converted into Java. Consider the code of the MainActivity file mentioned below for the conversion.
Step 2: Navigate to Tools Menu
From the topmost toolbar of the Android Studio, select Tools and then navigate to Kotlin > Show Kotlin Bytecode. It will open a window at the right-hand side that will contain the line by line bytecode for the Kotlin file.
Step 3: Decompile bytecode
In the bytecode window, checkbox the option “JVM 8 target” and click on Decompile. The Android Studio will generate the Java equivalent code for the Kotlin file. The produced java code will contain some additional information like metadata. Below is the generated Java code for the above mentioned Kotlin file.
Note: The Kotlin to Java code conversion will not create a new file in the project directory from where one can access the Java code. Thus to use the Android Studio generated Java code, one needs to copy it from the displayed decompiled java file.
Advantages of Java Over Kotlin
- Operator overloading is not possible.
- Classes written in Java are not made final by default.
- More readable syntax.
- Use of static methods and variables.