pdeva pdeva - 5 months ago 37
Java Question

What is the equivalent of Java static methods in Kotlin?

There is no

keyword in Kotlin.

What is the best way to represent a
Java method in Kotlin?


You place the function in the "companion object".

So the java code like this:

class Foo {
  public static int a() { return 1; }

will become

class Foo {
  companion object {
     int a() { return 1; }

From the docs:

Companion Objects

An object declaration inside a class can be marked with the companion keyword:

class MyClass {
   companion object Factory {
       fun create(): MyClass = MyClass()

Members of the companion object can be called by using simply the class name as the qualifier:

val instance = MyClass.create()

If you need to access these as statics from java, then the docs mention:

However, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the @JvmStatic annotation. See the Java interoperability section for more details.