0
0
Kotlinprogramming~5 mins

Calling Kotlin from Java

Choose your learning style9 modes available
Introduction

Sometimes you write code in Kotlin but want to use it in Java. Calling Kotlin from Java lets you mix both languages easily.

You have a Kotlin library and want to use it in a Java project.
You want to gradually add Kotlin code to an existing Java app.
You want to reuse Kotlin utility functions in Java classes.
You want to call Kotlin data classes or functions from Java code.
You want to combine Kotlin and Java for better code organization.
Syntax
Kotlin
KotlinClass kotlinObject = new KotlinClass();
kotlinObject.kotlinFunction();

From Java, you create Kotlin class instances like normal Java objects.

Kotlin functions and properties are accessed like Java methods and fields.

Examples
This Java class creates a KotlinGreeter object and calls its greet function.
Kotlin
public class JavaCaller {
    public static void main(String[] args) {
        KotlinGreeter greeter = new KotlinGreeter();
        System.out.println(greeter.greet("Alice"));
    }
}
This Java code calls a Kotlin top-level function 'add' inside the KotlinMath file.
Kotlin
public class JavaCaller {
    public static void main(String[] args) {
        int sum = KotlinMathKt.add(3, 5);
        System.out.println("Sum is: " + sum);
    }
}
Sample Program

This example shows a Kotlin class with a greet function. The Java class creates an object of KotlinGreeter and calls greet to print a message.

Kotlin
/* Kotlin file: KotlinGreeter.kt */

class KotlinGreeter {
    fun greet(name: String): String {
        return "Hello, $name!"
    }
}

/* Java file: JavaCaller.java */

public class JavaCaller {
    public static void main(String[] args) {
        KotlinGreeter greeter = new KotlinGreeter();
        System.out.println(greeter.greet("Alice"));
    }
}
OutputSuccess
Important Notes

Make sure Kotlin classes are compiled and visible to Java code in the same project or module.

Top-level Kotlin functions are accessed in Java via the generated class named after the Kotlin file with 'Kt' suffix.

Use @JvmStatic or @JvmName annotations in Kotlin to customize Java access if needed.

Summary

You can create Kotlin objects and call their functions from Java like normal Java objects.

Top-level Kotlin functions are accessed via special generated classes in Java.

Annotations in Kotlin help make calling from Java easier and clearer.