Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possibility to call a Java static method in Kotlin

Suppose we have a Java static method:

//Java code
public static void printFoo() {
    System.out.println("foo");
}

It is possible to call that method in Kotlin?

like image 504
Julys Pablo Avatar asked Feb 26 '15 04:02

Julys Pablo


People also ask

How do you call a static method in Kotlin?

In order to implement a static method in Kotlin, we will take the help of "companion objects". Companion objects are the singleton objects whose properties and functions are tied to a class but not to the instance of that class. Hence, we can access them just like a static method of the class.

Does Kotlin have static methods?

Kotlin is a statically typed programming language for the JVM, Android and the browser, 100% interoperable with Java. Blog of JetBrains team discussing static constants in Kotlin.

Do we have anything called static in Kotlin?

One way in which the Kotlin language differs from Java is that Kotlin doesn't contain the static keyword that we're familiar with. In this quick tutorial, we'll see a few ways to achieve Java's static method behavior in Kotlin.

Can you call a static method?

A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.


2 Answers

Yes, you can. Java code:

public class MyJavaClass {
    public static void printFoo() {
        System.out.println("foo");
    }
}

Kotlin code:

fun main(args: Array<String>) {
    MyJavaClass.printFoo()
}

So easy =)

like image 102
0wl Avatar answered Sep 20 '22 13:09

0wl


The answer from 0wl is generally correct.

I just wanted to add that some of the Java classes are mapped to special Kotlin classes. In this case you must fully qualify the Java class for this to work.

Example:

fun main(args: Array<String>) {
    println(java.lang.Long.toHexString(123))
}
like image 33
Eric Obermühlner Avatar answered Sep 19 '22 13:09

Eric Obermühlner