kotlin
  1. kotlin-calling-java-code-from-kotlin

Kotlin Calling Java Code from Kotlin

Kotlin is a modern programming language that can be used with Java programming language. It can be used for developing Android applications, server-side applications, and more. In this tutorial, we'll learn how to call Java code from Kotlin.

Syntax

To call Java code from Kotlin, you need to do the following:

  1. Import the Java class into your Kotlin file using the "import" statement.
  2. Create an instance of the Java class using the "new" keyword.
  3. Call the methods or properties of the Java object using the dot notation.

Example

Let's say we have a Java class called "Person" that has two fields, "firstName" and "lastName", and a method called "getFullName()" that returns the full name of the person.

public class Person {
    private String firstName;
    private String lastName;

    public String getFullName() {
        return firstName + " " + lastName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

Now, we want to call this Java class from our Kotlin code. We can do so by following the steps below:

import java.io.Person

fun main(args: Array<String>) {
    val person = Person()
    person.setFirstName("John")
    person.setLastName("Doe")
    println(person.fullName)
}

Output

When we run the above Kotlin code, we will get the following output:

John Doe

Explanation

To call Java code from Kotlin, we need to import the Java class using the "import" statement. Then, we can create an instance of the Java class using the "new" keyword. Once we have the instance, we can call the methods or properties of the Java object using the dot notation.

In the example above, we created a new instance of the "Person" class using the default constructor. We then set the first name and last name of the person using the "setFirstName()" and "setLastName()" methods. Finally, we called the "getFullName()" method using the "fullName" property of the person object.

Use

Calling Java code from Kotlin is useful when you have existing Java code that you want to reuse in your Kotlin application. This can save development time and effort, especially when you're developing Android applications.

Important Points

  • Make sure to import the correct Java class and package.
  • Ensure that you create an instance of the Java class before calling its methods or properties.
  • Be aware of any compatibility issues between Java and Kotlin datatypes.

Summary

In this tutorial, we learned how to call Java code from Kotlin. We covered the syntax, example, output, explanation, use, important points, and summary of calling Java code from Kotlin. With this knowledge, you can easily integrate your Java code with Kotlin applications and leverage the advantages of both programming languages.

Published on: