productFlavors: Kotlin and Java Coexistence

In a recent upgrade of an Android project to port existing Java files to Kotlin, I decided not to take advantage of the “Convert Java to Kotlin” shortcut provided by Android Studio, instead I took the following route:

  1. Rename to MyFile.orig
  2. Create MyFile.kt and rewrite the original Java class in Kotlin

and to protect my time investment in the original project, these two steps are repeatedly applied in a separate git branch.

For the first few Java classes, the above recipe works well until at some point I realize that the original Java files are useless in the current branch and building a Java-based APK requires a git-checkout to switch to the other branch.

But then ...

It dawned on me that Xavier Ducrohet mentioned productFlavors in one of his presentations at Google IO 2013, and I think this Gradle feature is a best-fit to solve my problem, i.e. placing both Java and Kotlin files of the same class co-exist in one

Gradle Settings

The following screenshot shows my app’s build.gradle file:

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

  • src/main: Java/Kotlin files shared by all the four build variants
  • src/kt: Kotlin files for building the ktDebug and ktRelease variants
  • src/jv: Java files for building the jvDebug and jvRelease 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 source files.

Related Posts

I found the following medium posts on using productFlavors, but could not find adequate details to solve my problem.