The first method of Java conversion is to convert an existing Java file into a Kotlin file. Let's walk through this conversion process with a simple example. We'll start with this simple Java ViewModel class:
We can see that this Java file currently resides within the same source directory as the Main.kt Kotlin file. This illustrates that Java and Kotlin code can exist, side by side, within the same directories. You don't have to concern yourself about isolating one language from the other.
We can convert this ViewModel class into Kotlin using the Convert Java File to Kotlin File tool within IntelliJ. To do so, follow these instructions:
- Navigate to Code | Convert Java File to Kotlin File.
- Use IntelliJ's Lookup Action shortcut and search for Convert Java File to Kotlin File:
- The IDE may then present you with the following dialog asking whether you wish to convert usages of the current file or class as well. Clicking OK will help to ensure the conversion doesn't break your application:
- Once converted, the file will now have a .kt extension and will be 100% Kotlin code. In most cases, this will result in less code that has common Kotlin idioms applied to it:
With our ViewModel example, the conversion reduces the code from 20 lines to 4. This type of file-by-file conversion from Java into Kotlin can be an effective strategy for migrating an existing code base to Kotlin. Because this conversion can happen at the file level, it gives a lot of flexibility in how the conversion strategy can be implemented. Development teams can migrate a single file, a module, or the whole code base to Kotlin however they see fit.
While migrating existing Java files is very helpful, sometimes, we may also want to convert a snippet of Java code without having to create a new Java file first. We'll take a look at how to manage this situation in the next section.