What is the equivalent of Java static methods in Kotlin?

Technology CommunityCategory: KotlinWhat is the equivalent of Java static methods in Kotlin?
VietMX Staff asked 3 years ago

Place the function in the companion object.

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

will become:

class Foo {
  companion object {
     fun a() : Int = 1
  }
}

// to run
Foo.a();

Another way is to solve most of the needs for static functions with package-level functions. They are simply declared outside a class in a source code file. The package of a file can be specified at the beginning of a file with the package keyword. Under the hood these “top-level” or “package” functions are actually compiled into their own class. In the above example, the compiler would create a class FooPackage with all of the top-level properties and functions, and route all of your references to them appropriately.

Consider:

package foo

fun bar() = {}

usage:

import foo.bar