Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Java Interoperability - Calling Java from Kotlin

One of the key strengths of Kotlin is its seamless interoperability with Java. You can call Java code from Kotlin and vice-versa with little to no friction. Let's walk through how to call Java code from Kotlin.

1. Setting Up:

If you're using Android Studio or IntelliJ IDEA, creating a mixed Java-Kotlin project is straightforward. For the purpose of this tutorial, you can add both Java and Kotlin files in the same project.

2. Simple Java Class:

Let's assume you have a simple Java class. Create a file named SimpleJavaClass.java:

public class SimpleJavaClass {
    public static String sayHello() {
        return "Hello from Java!";
    }
    
    public int add(int a, int b) {
        return a + b;
    }
}

3. Calling Java from Kotlin:

Now, create a Kotlin file named Main.kt:

fun main() {
    // Calling a static method from a Java class
    val message = SimpleJavaClass.sayHello()
    println(message)
    
    // Creating an instance of the Java class and calling an instance method
    val javaInstance = SimpleJavaClass()
    val sum = javaInstance.add(5, 3)
    println("Sum: $sum")
}

4. Java Interoperability Nuances:

While basic interoperability is straightforward, there are some nuances to be aware of:

  1. Null Safety: Kotlin's type system distinguishes between nullable and non-nullable references. Java doesn't have this distinction. Therefore, types declared in Java are treated as platform types in Kotlin, which means Kotlin doesn't enforce null-safety on them at compile-time. It's the developer's responsibility to handle nullability when working with Java objects.

    val javaObject: SomeJavaClass = getJavaObject()  // This might be null
    
  2. Getters and Setters: Kotlin's property syntax is smoothly mapped onto Java's getter-setter patterns. So, if you have a Java class with a getter getName() and a setter setName(String), you can use it in Kotlin as if it's a property.

    javaInstance.name = "Kotlin"
    println(javaInstance.name)
    
  3. SAM Conversions: If a Java interface has only one abstract method (Single Abstract Method or SAM interface), you can use a lambda when instantiating it in Kotlin.

    javaInstance.setClickListener { view -> println("View clicked!") }
    
  4. Extension Functions: If you want to add utility functions to Java classes without modifying their code, you can use Kotlin's extension functions.

    fun SimpleJavaClass.isPositive(): Boolean {
        return this.add(1, 2) > 0
    }
    

5. Conclusion:

Kotlin's interoperability with Java is one of the key features that has facilitated its adoption, especially in the Android community. It allows developers to adopt Kotlin gradually, migrating parts of their codebase over time. With the concepts discussed above, you should be comfortable using Java code within your Kotlin projects.

  1. Kotlin and Java interoperability examples: Example 1 - Calling Java method in Kotlin:

    // Kotlin code
    val result = JavaClass.javaMethod()
    

    Example 2 - Using Java class in Kotlin:

    // Kotlin code
    val javaObject = JavaClass()
    javaObject.javaMethod()
    
  2. Using Java libraries in Kotlin: Kotlin can easily use Java libraries by adding them to the classpath. Simply import and use the Java classes as if they were written in Kotlin.

    // Kotlin code using a Java library
    import java.util.ArrayList
    
    val list = ArrayList<String>()
    list.add("Kotlin")
    
  3. Calling Java methods from Kotlin code:

    // Kotlin code calling a Java method
    val result = JavaClass.javaMethod()
    
  4. Working with Java classes in Kotlin: Kotlin can work with Java classes as if they were Kotlin classes. You can instantiate Java objects, call methods, and access fields without any issues.

    // Kotlin code working with a Java class
    val javaObject = JavaClass()
    javaObject.javaMethod()
    
  5. Accessing Java fields and methods in Kotlin: Kotlin can access Java fields and methods using the standard dot notation.

    // Kotlin code accessing Java field
    val value = javaObject.javaField