How to Convert a Kotlin File to a Java File

Android Studio supplies full assistance for Kotlin, which allows you to include Kotlin files in your existing project and transform Java language code to Kotlin. And then, you can use all of Android Studio's existing tools with your Kotlin code, consisting of autocomplete, lint checking, refactoring, debugging, etc.

Kotlin is popular for its interoperability with Java. This is possible due to the fact that they both are working on the Java Virtual Machine. That is to say, they are assembled to the very same bytecode.

On this page, we'll introduce one of the most useful ways to achieve the conversion from a Kotlin file to a Java file.

How to Convert Using Command Line Tools

1. Let's suppose that we have a Kotlin file name as Sample.kt. See as below.

enjoyable printEvenNumbers()

Then, let's assemble the code with the command listed below. By doing this, a file named SampleKt.class will be created.

kotlinc Sample.kt.

2. Now, we should decompile this file into Java.

How to do it? Simply use FernFlower. We can get the fernflower.jar by downloading the task and running the Gradle build. When we have the JAR file, use the following command to run.

java -container fernflower.jar SampleKt.class

3. Finally, we can see the file SampleKt.java.

import kotlin.Metadata;
import kotlin.ranges.IntProgression;
import kotlin.ranges.IntRange;
import kotlin.ranges.RangesKt;

@Metadata(
   mv = {1, 1, 15},
   bv = {1, 0, 3},
   k = 2,
   d1 = 
     {"\u0000\u0006\n\u0000\n\u0002\u0010\u0002\u001a\u0006\u0010\u0000\u001a\u00020\u0001"},
   d2 = {"printEvenNumbers", ""}
)
public final class SampleKt {
   public static final void printEvenNumbers() {
      byte var3 = 0;
      IntProgression var10000 = RangesKt.step((IntProgression)(new IntRange(var3, 10)), 2);
      int i = var10000.getFirst();
      int var1 = var10000.getLast();
      int var2 = var10000.getStep();
      if (var2 >= 0) {
         if (i > var1) {
            return;
         }
      } else if (i < var1) {
         return;
      }

      while(true) {
         boolean var4 = false;
         System.out.println(i);
         if (i == var1) {
            return;
         }

         i += var2;
      }
   }


Leave a reply



Submit