What is the equivalent of Java static methods 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 {
fun a() : Int = 1
}
}
You can then use it from inside Kotlin code as
Foo.a();
But from within Java code, you would need to call it as
Foo.Companion.a();
(Which also works from within Kotlin.)
If you don't like having to specify the Companion
bit you can either add a @JvmStatic
annotation or name your companion class.
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()
...
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.
Adding the @JvmStatic
annotation looks like this
class Foo {
companion object {
@JvmStatic
fun a() : Int = 1;
}
}
and then it will exist as a real Java static function, accessible from
both Java and Kotlin as Foo.a()
.
If it is just disliked for the Companion
name, then you can also
provide an explicit name for the companion object looks like this:
class Foo {
companion object Blah {
fun a() : Int = 1;
}
}
which will let you call it from Kotlin in the same way, but
from java like Foo.Blah.a()
(which will also work in Kotlin).
Docs recommends 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.
Declaration
package foo
fun bar() = {}
Usage
import foo.bar
Alternatively
import foo.*
You can now call the function with:
bar()
or if you do not use the import keyword:
foo.bar()
If you do not specify the package the function will be accessible from the root.
If you only have experience with java, this might seem a little strange. The reason is that kotlin is not a strictly object-oriented language. You could say it supports methods outside of classes.
Edit: They have edited the documentation to no longer include the sentence about recommending package level functions. This is the original that was referred to above.
A. Old Java Way :
Declare a
companion object
to enclose a static method / variableclass Foo{ companion object { fun foo() = println("Foo") val bar ="bar" } }
Use :
Foo.foo() // Outputs Foo println(Foo.bar) // Outputs bar
B. New Kotlin way
Declare directly on file without class on a
.kt
file.fun foo() = println("Foo") val bar ="bar"
Use the
methods/variables
with their names. (After importing them)Use :
foo() // Outputs Foo println(bar) // Outputs bar