Possibility to call a Java static method in Kotlin
Asked Answered
R

4

10

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?

Raphaelraphaela answered 26/2, 2015 at 4:30 Comment(0)
B
19

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

Biddle answered 26/2, 2015 at 20:2 Comment(2)
but from instance is not?Sailesh
How could we call android.nfc.Tag.createMockTag from Kotlin?Fitment
D
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))
}
Drove answered 15/12, 2017 at 15:0 Comment(0)
M
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.

Moresque answered 26/2, 2015 at 4:48 Comment(0)
W
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.

Weald answered 3/10, 2021 at 17:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.