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

In my Kotlin project, I have some parts of Java code that I want to convert to Kotlin. The menu item that converts the Java file to Kotlin is disabled because it's not a whole file I want to convert.

How can I convert Java code to Kotlin?


Solution 1:

With Android Studio 3.0

You don't need to install any plugin to convert java code to kotlin code. Now, Google is officially supporting Kotlin language.

  • Android Studio Menu -> Code -> Convert Java File to Kotlin File

Before Android Studio 3.0

If you are using older Android Studio ( which is below version 3.0 ) there is a Kotlin tool under the menu.

Installing Kotlin plugin :

  • Android Studio Menu -> File -> Settings -> Plugins -> Browse repositories -> Kotlin

Converting Java Code to Kotlin Code :

  • Select your java class file from project structure.
  • Android Studio Menu -> Code -> Convert Java File to Kotlin File

Solution 2:

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.

Solution 3:

To convert Java code in Android studio use CTRL+SHIFT+ALT+K

To convert from Website use Try Kotlin site.

To convert from Android app use Master in Android.

Solution 4:

I found a workaround:

  1. Create a Java file and paste inside this file Java code, which you want to convert.
  2. Now copy Java code from Java file.
  3. Go to the Kotlin file and paste this code. IDEA will suggest convert code from Java to Kotlin.