How to Convert a Part of Java Source File to Kotlin

How can I convert a part of Java source file to Kotlin?

There is no tool to convert Kotlin code to Java. If you want to convert part of a file from Java to Kotlin, the easiest way is to copy the code from the Java file in the IDE and paste it into the Kotlin file.

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

As @Vadzim said, in IntelliJ or Android Studio, you just have to do the following to get java code from kotlin:

  1. Menu > Tools > Kotlin > Show Kotlin Bytecode
  2. Click on the Decompile button
  3. Copy the java code

Update:

With a recent version (1.2+) of the Kotlin plugin you also can directly do Menu > Tools > Kotlin -> Decompile Kotlin to Java.

How does Convert Java File to Kotlin File work?

The tool uses the IntelliJ IDEA PSI interface to parse and analyze the Java source code and then converts the resulting tree into Kotlin text. It's open-source just like everything else related to Kotlin; you can find the implementation here.

In Android Studio, pasting Java code into a Kotlin file doesn't convert to Kotlin anymore

Sometimes the IDE it does not convert because its complexity, just try to convert a simple method with a SOPLN and check if it works.

By the way if you want to convert a Java file to a Kotlin one remember that you have the Action of :

Sample Image

Is converting a Kotlin file to java, adding java code to it and converting back to Kotlin same as adding code directly to the Kotlin file?

The Kotlin decompiler is not for converting Kotlin code back to Java and actually using that code. It's to give you an idea of what bytecode your Kotlin code is compiled to, only with the familiar Java syntax, since most people can't read the bytecode directly. The decompiled Java code often isn't even executable without putting in additional work to fix it.

The Java to Kotlin compiler is meant to give you working Kotlin code from existing Java code, however, even that can't produce nice, idiomatic Kotlin.

Combining these two imperfect conversions (if it somehow works) will not get you to the original Kotlin code with just your new modifications, it's likely to mess all the converted code up significantly. For an analogue, think of it as translating a sentence with Google Translate through several different languages, and then going back to the original.

If you wish to contribute to an open source project that uses Kotlin, it's much easier and much more feasible to just learn Kotlin. It's really quite easy to pick it up if you already know Java.



Related Topics



Leave a reply



Submit