What is the equivalent of Java static methods in Kotlin?

0 votes
asked Feb 5, 2020 by Hitesh Garg (799 points)  

Since there is no static keyword in Kotlin.
How do I write static variables and methods in Kotlin?

2 Answers

0 votes
answered Feb 7, 2020 by Hitesh Garg (799 points)  
selected Sep 28, 2021 by Hitesh Garg
Best answer

"companion object" is the alternative for static fields and methods in Java.

So the java code like this:

class Foo {
  public static String a() { return "hello"; }

In kotlin will look like

class Foo {
  companion object {
     fun a() : String = "hello"

You can then use it from inside Kotlin code as

0 votes
answered Jun 4, 2021 by Stella Aldridge (20 points)  

I've got the same question when I learn java. Lucky you are, cause "companion" objects are really the most similar to what you're looking for. You may have a look here for more details https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects.
It will be shown like Foo is Object Foo { ... } in Kotlin via its compiler.
This annotation - @JvmStatic is used in case you want the field to be static.

Hope it helps.