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?
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.
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.
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.
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.
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 =)
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With