Introduction

Having looked at the core capabilities of the language, let’s now turn our attention to applying Kotlin. In this part, you’ll learn how to use Kotlin with Spring and to create Android applications. You’ll also learn how to use Kotlin with Gradle and Maven and, along the way, pick up some techniques for unit testing Kotlin code with tools like KotlinTest and Mockk. We’ll also explore the options to interoperate between Java and Kotlin code running side by side.

The focus of this book is Kotlin for developers familiar with Java, and in this chapter, we’ll take a look at intermixing Kotlin and Java code. We’ll first look at calling Java code from Kotlin. Then we’ll dive into the intricacies of calling Kotlin code from Java.

If your application is being developed predominantly using Kotlin, you may use Java libraries in your projects as much as you want. You may even intermix Kotlin source files and Java source files in your projects, if you like. You’ll see in this chapter that calling Java code from within Kotlin is straightforward, and the issues you’ll run into are minimal and easy to resolve.

If your application is mostly written in Java, you may use Kotlin libraries or even intermix Kotlin source files in your projects. Since Kotlin has special features that are not available in Java—default arguments, to mention one example—the authors of the Kotlin code have to take extra measures if they intend to make the code properly available for calls from Java. While calling code written in Kotlin from other Kotlin code is natural and effortless, calling the code from Java takes effort. In this chapter, we’ll discuss various measures you have to take to make your Kotlin code available for practical use from Java.

We’ll first look at why and how to mix Kotlin and Java source files in the same project. Then we’ll explore calling Java code from within Kotlin and how to resolve some minor glitches you may run into. After that, for most of this chapter,​ we’ll focus on how to prepare Kotlin code for use from Java.


Get hands-on with 1400+ tech skills courses.