Interoperable Kotlin

Its interoperability with Java is perhaps among Kotlin features that attracts many Android programmers to incorporate this relatively new programming language (21 years younger than Java) into their Android projects.

Then it’s time to make my feet wet by using Kotlin in a real project. I picked one of our existing projects and began Kotlin-izing the Java classes. However, I decided not to take the shortcut provided by Android Studio intentions “Convert Java to Kotlin”. Instead, I invoked Android Studio menu Refactor => Rename File to rename the original file then created a new Kotlin file that implements original Java class. Doing this manual labor one class at a time in a separate git branch is a rewarding experience as your more about Kotlin idiomatic expressions.

While I get the benefit of reusing the existing Android resources in the project (drawables, strings, styles, animation, etc) I also realized that the old Java files are just sitting there useless. In addition, if anytime I wanted to regenerate the original Java-based APK, I had to run git-checkout to switch branch. I then challenged myself to go beyond proofing the interoperability of the two languages: How do I keep two implementations of the same class in both Java and Kotlin in one Android project?

Coexistence: Beyond Interoperable

After tinkering with Gradle settings, it dawned on me that Xavier Ducrohet (one of the developers on the Android Tools team) mentioned a practical use of productFlavor to customize Android builds in a presentation at Google IO 2013 (you can just to minute mark 14:13) and I think this Gradle feature is the perfect solution to my challenge.

This is how I set my application build.gradle:

Using these settings, I organize my files into the following three subdirectories:

  • src/main: Java/Kotlin files shared by all the four build variants
  • src/jv: Java files for building the jvDebug and jvRelease variants
  • src/kt: Kotlin files for building the ktDebug and ktRelease variants

 

Switching the build variant in Android Studio automatically updates the Android Project view and allows me to quickly edit either the Java or Kotlin version of the same class.

You can also find our post on this subject on Medium.