Welcome to our Kotlin Java Calling Kotlin tutorial! Today, we'll explore how to call Java code from Kotlin and vice versa, making them interoperable. By the end of this lesson, you'll have a solid understanding of this essential concept for any developer working with both languages. 📝
Kotlin is a modern, statically-typed programming language that runs on the Java Virtual Machine (JVM). This means that Kotlin can easily call Java methods and use Java libraries. On the other hand, Java can also call Kotlin methods. This interoperability saves time and effort for developers who want to leverage the benefits of both languages in their projects.
Let's create a simple Java class named JavaExample with a method called sumTwoNumbers:
// JavaExample.java
public class JavaExample {
public int sumTwoNumbers(int a, int b) {
return a + b;
}
}Now, we'll call the sumTwoNumbers method from Kotlin:
// Main.kt
import java.lang.JavaClass
fun main() {
val javaExample = JavaClass.forName("JavaExample")
.newInstance() as JavaExample
val result = javaExample.sumTwoNumbers(5, 7)
println("The sum of two numbers is $result")
}Compile and run the project, and you should see the following output:
The sum of two numbers is 12
Let's create a Kotlin class named KotlinExample with a method called greetUser:
// KotlinExample.kt
class KotlinExample {
fun greetUser(name: String) {
println("Hello, $name!")
}
}Now, we'll call the greetUser method from Java:
// Main.java
import org.jetbrains.kotlin.js.runtime.jsInterface;
public class Main {
public static void main(String[] args) {
KotlinExample kotlinExample = new KotlinExample();
kotlinExample.greetUser("John Doe");
}
}
@jsInterface
public interface KotlinExampleInterface {
void greetUser(String name);
}Compile and run the project, and you should see the following output:
Hello, John Doe!
What is the purpose of the Kotlin Java interoperability?
That's all for today! We hope you enjoyed learning about Kotlin Java calling Kotlin. With this newfound knowledge, you can start exploring the vast ecosystem of Java libraries from within your Kotlin projects and vice versa. Happy coding! 💡🎯