Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting file (tracked with Git) from Java to Kotlin in Android Studio

A conversion from Java to Kotlin in Android Studio 2.3.2 (in 3.0 the same behaviour) creates a new file and deletes previous. So Git doesn't know anything about this conversion. And the git history doesn't save. In Intellij Idea everything's fine. IDE just renames file and git saves the history. How can do the same in Android Studio.

like image 773
Eugene Verichev Avatar asked Jun 01 '17 14:06

Eugene Verichev


People also ask

Can we convert Android Java to Kotlin?

To convert Java code to Kotlin, open the Java file in Android Studio, and select Code > Convert Java File to Kotlin File. Alternatively, create a new Kotlin file (File > New > Kotlin File/Class), and then paste your Java code into that file.

How do I move a Java project to Kotlin?

Go to the User. java file and convert it to Kotlin: Menu bar -> Code -> Convert Java File to Kotlin File.

Can you use Kotlin and Java in the same project Android Studio?

Adding Java source code to an existing Kotlin projectIf you already have the Java classes, you can just copy them to the project directories. You can now consume the Java class from Kotlin or vice versa without any further actions. lets you call it from Kotlin like any other type in Kotlin.

Can Java be converted to Kotlin?

You can use both Android Studio and IntelliJ IDE software to convert Java code to Kotlin. If you are using a Kotlin based project in Android Studio or IntelliJ IDE software and try to copy/paste Java code, you should get a prompt to automatically convert Java code to Kotlin (as shown in the screenshot below).


2 Answers

Git guesses renames from added/removed file pairs, but only if these files are close enough, i.e. if the file was renamed with no or small amount of changes.

When you apply java-to-kotlin conversion usually every line of a file changes, so that git cannot find that these old and new files somehow relate to each other.

You can use the following two-stage approach instead:

  • just change the extension of .java file to .kt and commit it;
  • rename it back, apply the conversion and commit the modified .kt file.
like image 119
Ilya Avatar answered Oct 05 '22 17:10

Ilya


In case this might help a future reader:

If you use the Git commit dialog integrated with IntelliJ (Commit via Ctrl+K), there is a checkbox on the right in recent versions: ☑ Extra commit for .java > .kt renames

Submitting the dialog this way will create two commits, the first one being just .java files renamed into .kt files with no content changes. This helps Git track the content.

like image 26
Hay Avatar answered Oct 05 '22 18:10

Hay