Migrating from Java to Kotlin
Are you a Java developer and have your apps in Java? Are you wondering how you could get started with Kotlin? Worry not, this is your section. Kotlin offers two ways for you:
- Java-to-Kotlin migration: The IDE that we are using, IntelliJ IDEA, has a tool for converting existing Java files to Kotlin.
- Interoperability: Kotlin is highly interoperable with Java code, meaning you can have both Java and Kotlin code in the same project. You can continue using your favorite Java libraries in your Kotlin projects.
Let’s see how to migrate a sample Java class to Kotlin using IntelliJ IDEA:
- Inside
src/main/kotlin
, open theSong
class, which has a number of Java functions. - Right-click the file and you’ll see the Convert Java to Kotlin option at the bottom. Select this and you’ll be presented the following confirmation dialog:
Figure 1.4 – Confirmation dialog
At times after a conversion, you might need to make some corrections and that’s why we have this dialog. Click Yes to proceed and you’ll see your code is now in Kotlin. This is a useful feature that handles a major part of the conversion to Kotlin and you also learn about the syntax.
Now that we’ve learned how to migrate Java code to Kotlin, in the next section we will cover some of the features of Kotlin that make it useful for Android developers.