Sometimes you write code in Kotlin but want to use it in Java. Calling Kotlin from Java lets you mix both languages easily.
Calling Kotlin from Java
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.
public class JavaCaller { public static void main(String[] args) { KotlinGreeter greeter = new KotlinGreeter(); System.out.println(greeter.greet("Alice")); } }
public class JavaCaller { public static void main(String[] args) { int sum = KotlinMathKt.add(3, 5); System.out.println("Sum is: " + sum); } }
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 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")); } }
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.
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.