Edit Page

Mixing Java and Kotlin in one project

Last Updated 11 April 2019
This tutorial walks us through the process of using Java and Kotlin in a single IntelliJ IDEA project.

We'll be using IntelliJ IDEA (Ultimate or Community edition). To learn how to start a new Kotlin project in IntelliJ IDEA, see the Getting Started with IntellJ IDEA tutorial. If you are using build tools, please see the corresponding entry under Build Tools.

Adding Java source code to an existing Kotlin project

Adding Java classes to a Kotlin project is pretty straightforward. All you need to do is create a new Java file (Alt + Insert/Cmd + N) in the correct directory or package.

New Java Class

If you already have the Java classes, you can just copy them to the project directories.

You can now consume the Java сlass from Kotlin or vice versa without any further actions.

For example, adding the following Java class:

public class Customer {

    private String name;

    public Customer(String s){
        name = s;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public void placeOrder() {
        System.out.println("A new order is placed by " + name);
    }
}

lets you call it from Kotlin like any other type in Kotlin.

val customer = Customer("Phase")
println(customer.name)
println(customer.placeOrder())

Adding Kotlin source code to an existing Java project

Adding a Kotlin file to an existing Java project is pretty much the same process.

New Kotlin File

If this is the first time you're adding a Kotlin file to this project, IntelliJ IDEA will prompt you to add the required Kotlin runtime. For a Java project, configure the Kotlin runtime as a Kotlin Java Module.

The next step is to decide which modules to configure (if the project has more than one module) and whether you want to add the runtime library to the project or use those provided by the current Kotlin plugin.

Bundling Kotlin Runtime

You can also open the Kotlin runtime configuration manually from Tools | Kotlin | Configure Kotlin in Project.

Converting an existing Java file to Kotlin with J2K

The Kotlin plugin also bundles a Java to Kotlin converter (J2K) that automatically converts Java files to Kotlin. To use J2K on a file, click Convert Java File to Kotlin File in its context menu or in the Code menu of IntelliJ IDEA.

Convert Java to Kotlin Menu

While the converter is not fool-proof, it does a pretty decent job of converting most boilerplate code from Java to Kotlin. Some manual tweaking however is sometimes required.