Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Calling Java from Kotlin

Introduction

Kotlin is fully interoperable with Java, allowing developers to call Java code from Kotlin and vice versa. This feature is particularly useful when you want to leverage existing Java libraries or APIs in your Kotlin applications. In this tutorial, we will explore how to call Java classes and methods from Kotlin with clear examples.

Setting Up Your Environment

Before you start, ensure you have the following set up in your development environment:

  • Java Development Kit (JDK) installed.
  • Kotlin compiler installed.
  • An IDE that supports Kotlin (e.g., IntelliJ IDEA).

Creating a Simple Java Class

Let’s create a simple Java class that we will call from Kotlin. Create a file named Calculator.java with the following code:

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }
}
                

This class provides two basic arithmetic operations: addition and subtraction.

Calling Java Class from Kotlin

Next, we will create a Kotlin file to call the Calculator class. Create a file named Main.kt with the following code:

fun main() {
    val calculator = Calculator()
    val sum = calculator.add(5, 3)
    val difference = calculator.subtract(5, 3)

    println("Sum: $sum")
    println("Difference: $difference")
}
                

In this Kotlin code, we create an instance of the Calculator class and call the add and subtract methods.

Compiling and Running the Code

To run this code, you need to compile both the Java and Kotlin files. Use the following commands in your terminal:

javac Calculator.java
kotlinc Main.kt -include-runtime -d Main.jar
java -jar Main.jar
                

After executing these commands, you should see the following output:

Sum: 8
Difference: 2
                

Handling Java Exceptions in Kotlin

Kotlin has its own way of handling exceptions, but you can also catch Java exceptions. Here’s an example of how to do that:

fun main() {
    val calculator = Calculator()
    try {
        val result = calculator.divide(10, 0)
        println("Result: $result")
    } catch (e: ArithmeticException) {
        println("Caught an exception: ${e.message}")
    }
}
                

In this code, we attempt to divide by zero, which throws an ArithmeticException. We catch and handle this exception in Kotlin.

Conclusion

In this tutorial, we learned how to call Java code from Kotlin with examples of creating a Java class and invoking its methods from Kotlin. We also covered how to handle exceptions thrown by Java code. This interoperability allows you to effectively utilize existing Java libraries and frameworks in your Kotlin applications.