Converting an Android app to Kotlin (part 1)

In this article, I will take you through the steps of converting an Android app to Kotlin. We will use the awesome Cheesesquare sample by Chris Banes. Firstly, here’s what the app’s UI looks like:

As you can see, it demonstrates the use of Android Design Library and Material Design. This includes the following UI features:

  • Collapsing Toolbar
  • FloatingActionButton
  • View anchoring
  • NavigationView
  • Snackbar

As I stated above, this project was originally written in Java. So let’s dive in and convert the code to Kotlin. As you may be aware, the visual launch point for any Android app is the Activity specified with MAIN, DEFAULT, and LAUNCHER tags in AndroidManifest.xml. Hence, this app’s launch activity is MainActivity.java. So, let’s start by converting its code to Kotlin:

convert java file to kotlin

As you can see in the above image, we just clicked ‘Code’ -> ‘Convert Java File to Kotlin File’ in Android Studio. As a result, we got this .kt file that replaced the .java file:

One more caveat: if you want to run this app which Kotlin code without crashing, you need to add this to your app module’s build.gradle file:

apply plugin: 'kotlin-android'
repositories {
maven {
url 'http://dl.bintray.com/kotlin/kotlin-eap-1.2'
}
}

Perfect, now you have a Kotlin file that replaced your Java file without much effort! Run the app, and you’ll see it behaves the exact same way as before. In part 2 of this blog series, we’ll inspect this new Kotlin file and find ways to optimize it.

Thank you for reading!

Gurupriyan is a Software Engineer and a technology enthusiast, he’s been working on the field for the last 6 years. Currently focusing on mobile app development and IoT.

Please follow and like us:
0