Java Interoperability

There is a decent chance that you are interested in using Kotlin for Android app development, as there is a lot of Kotlin momentum in that space.

You might also be interested in using Kotlin in other places alongside Java:

Throughout the book to this point, there have been a few notes about Kotlin running on the Java Virtual Machine (JVM). Everything that you have learned so far works for Kotlin/JVM. In this chapter, we focus on things that you may have to do to get your Kotlin code to work alongside Java code, whether that is Kotlin calling into Java (e.g., the Android SDK) or Java calling into Kotlin (e.g., legacy Java code in your app).

Recap of Interoperability

As was covered back in the first chapter, there are a number of layers to Kotlin with respect to environments.

A lot of Kotlin is what is considered nowadays to be Kotlin/Common. This code works on all environments that Kotlin can run on.

Kotlin then has three variants (at present) for running on specific environments:

The implementations of some things may vary based on environment. For example, the Regex class for working with regular expressions has different rules for Kotlin/JVM, Kotlin/JS, and Kotlin/Native. While the class always exists, the regular expression pattern language may differ, as Regex defers to an environment-supplied implementation.

But beyond that, you may need to add some stuff to your code base to be able to interoperate with code specific for an environment, such as Java code for Kotlin/JVM or JavaScript code for Kotlin/JS. While Kotlin aims to make it relatively painless to bridge languages, there are still differences that need to be resolved. This chapter will focus on those involving Java.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.