8

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?

Naetmul
  • 14,544
  • 8
  • 57
  • 81
Julys Pablo
  • 145
  • 1
  • 1
  • 8

4 Answers4

17

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 =)

0wl
  • 836
  • 8
  • 19
2

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))
}
Eric Obermühlner
  • 1,076
  • 9
  • 9
1

Yes. It's documented in the Java Interop

http://kotlinlang.org/docs/reference/java-interop.html

The docs show the following example

if (Character.isLetter(a)) {
 // ...
}

The only caveat I see is that they can't be passed around with an instance and accessed on instances of the class like you can in Java but this is usually considered bad practice anyway.

Lionel Port
  • 3,492
  • 23
  • 26
0

In Java it is possible to call static methods from child classes, in Kotlin this is not possible. If this is your case, call the method from the parent, instead.

Test.java:

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

Test2.kt:

class Test2: Test()

// Test2.printFoo() // doesn't work
Test.printFoo() // Works

Refer to this StackOverflow thread for more information.

Maicon Mauricio
  • 2,052
  • 1
  • 13
  • 29