Joint Compilation
We'll cover the following
How to intermix code
You can intermix code written using Java and Kotlin two different ways:
-
Bring code written in either of those languages into a Java or Kotlin project as a JAR file dependency.
-
Have source files written in the two languages, side by side, in a project.
The first approach is the most common. Currently you bring dependencies from Maven or JCenter into your Java projects using a build tool like Maven or Gradle. Likewise, you can bring dependencies into your Kotlin projects. The JAR files your code depends on may be created from Java, Kotlin, or both. If there are no compatibility issues, using these JAR files written in Kotlin or Java feels natural, just like using Java JAR files in Java projects. Any compatibility issues that may surface will be due to the language differences and not due to the JAR file integration. The techniques discussed later in this chapter will help resolve those issues.
The second approach, of mixing both Java and Kotlin source code in one project, is an option if you’re introducing Kotlin into legacy Java projects and you want to make use of the power of Kotlin in some areas of the application.
Obviously, to compile the code written in the two different languages, you’ll have to use the compilers of the respective languages. However, complications will arise from interdependencies.
Suppose your Kotlin code is calling some of your Java code, and some of your Java code is calling your Kotlin code. Compiling Java code first will fail since the Kotlin code it depends on hasn’t been compiled yet into bytecode. Thankfully, this situation can be resolved by running the Kotlin compiler first and then the Java compiler. For this method to work, you must provide both the Kotlin source files and the Java source files to the Kotlin compiler. Upon seeing the Java source files, the Kotlin compiler will create stubs for the classes and methods in the given Java source files so that the dependencies of the Kotlin code are satisfied. Once the bytecode from the Kotlin code is generated, when you run the Java compiler, it will find the necessary Kotlin code dependencies for the Java code.
If you’re using Maven or Gradle to run your build, then refer to the documentation to set up the project for joint compilation.
Irrespective of the tools you use to build, running the compilations from the command line will give a clear view of the underlying mechanism. For that reason, let’s explore compiling code for a small sample project that mixes source files from both Java and Kotlin.
The following project contains two Kotlin source files under the directory jointcompilation/src/main/kotlin/com/agiledeveloper/joint
and one Java source file under the directory jointcompilation/src/main/java/com/agiledeveloper/joint
. The Constants
class written in Kotlin doesn’t have any dependencies, and we’ll take a look at that first:
Get hands-on with 1400+ tech skills courses.